Esempio n. 1
0
        //also reference to Algorithm.TreeAndGraph.Floyd and Algorithm.TreeAndGraph.Dijkstra
        public static int getShortestDistance(TreeAndGraph.GraphNode start, TreeAndGraph.GraphNode end)
        {
            System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<TreeAndGraph.GraphNode>> tab
                = new System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<TreeAndGraph.GraphNode>>();
            System.Collections.Generic.List<TreeAndGraph.GraphNode> list = new System.Collections.Generic.List<TreeAndGraph.GraphNode>();
            int count = 1;
            list.Add(start);
            tab.Add(count, list);
            while (true)
            {
                System.Collections.Generic.List<TreeAndGraph.GraphNode> gn_list = tab[count];
                ++count;
                if (!tab.ContainsKey(count))
                {
                    list = new System.Collections.Generic.List<TreeAndGraph.GraphNode>();
                    tab.Add(count, list);
                }
                foreach (TreeAndGraph.GraphNode gn in gn_list)
                {

                    foreach (TreeAndGraph.GraphNode node in gn.Nodes)
                    {
                        if (node == end)
                        {
                            return count;
                        }

                        tab[count].Add(node);
                    }
                }
            }
        }
        public string GetSystemData()
        {
            string str;
            UserInfo user;
            if (IsAuthenticated(out str) && GetUser(out user, ref str))
            {
                str += string.Format(", \"profile\": {{ \"userid\":{0}, \"displayname\":\"{1}\", \"image\":\"{2}\", \"IsSuperuser\":{3} }}, \"contacts\":[",
                    user.UserID, user.DisplayName, user.Image, user.IsSuperuser.ToString().ToLower());
                System.Collections.Generic.Dictionary<int, string> contacts = new System.Collections.Generic.Dictionary<int, string>();
                foreach (ContactInfo info in ContactInfo.GetContacts(user.UserID))
                {
                    UserInfo contactuser = UserInfo.Get(info.ContactID);
                    if (!contacts.ContainsKey(info.GroupID))
                        contacts.Add(info.GroupID, "{ \"groupid\": " + info.GroupID + ", \"groupname\": \"" + info.GroupName + "\", \"users\":[");
                    contacts[info.GroupID] += contactuser.ToJSON() + ",";
                }
                foreach (System.Collections.Generic.KeyValuePair<int, string> g in contacts)
                    str += g.Value.Remove(g.Value.Length - 1) + "] },";

                str = str.Remove(str.Length - 1) + "], \"topics\": [ ";
                foreach (TopicInfo info in TopicInfo.GetByUser(user.UserID))
                    str += string.Format("{{ \"id\":{0}, \"title\":\"{1}\" }},", info.TopicID, info.GetTitle());

                str = str.Remove(str.Length - 1) + "]";
            }
            return str;
        }
        private void SetHourData(Models.Student student, ExcelWorksheet worksheet)
        {
            var collector = new System.Collections.Generic.Dictionary<SpreadsheetExport.Key, int>();
            foreach (var b in student.Behaviors) {
                var key = new SpreadsheetExport.Key { DayOfWeek = b.TimeRecorded.DayOfWeek.ToString(), Hour = b.TimeRecorded.Hour };
                if (collector.ContainsKey(key))
                    collector[key] += 1;
                else
                    collector.Add(key, 1);

            }
            foreach (var key in collector.Keys) {
                var value = key.Hour - 2;
                switch (key.DayOfWeek.ToString()) {
                    case "Monday": worksheet.Cells[5, value].Value = collector[key];
                        break;
                    case "Tuesday": worksheet.Cells[6, value].Value = collector[key];
                        break;
                    case "Wednesday": worksheet.Cells[7, value].Value = collector[key];
                        break;
                    case "Thursday": worksheet.Cells[8, value].Value = collector[key];
                        break;
                    case "Friday": worksheet.Cells[9, value].Value = collector[key];
                        break;
                    default:
                        break;
                }
            }
        }
        public static LinkedList<int> RemoveDuplicateFromUnsortedList(LinkedList<int> linkedList)
        {
            if (linkedList == null)
                throw new ArgumentNullException("linkedList");

            var hash = new System.Collections.Generic.Dictionary<int, bool>();
            LinkedListNode<int> currentNode = linkedList.Root;
            LinkedListNode<int> previous = null;

            while (currentNode != null)
            {
                int data = currentNode.Data;
                if (hash.ContainsKey(data))
                {
                    previous.Next = currentNode.Next;
                }
                else
                {
                    hash.Add(data, true);
                    previous = currentNode;
                }
                currentNode = currentNode.Next;
            }
            return linkedList;
        }
Esempio n. 5
0
        public void EditVoid()
        {
            byte[] bytes = new byte[] { 240, 1, 14, 239, 55, 55 };
            MacAddress expected = new MacAddress(bytes);
            var result = new System.Collections.Generic.Dictionary<MacAddress, string> {{expected, "ok"}};

            MacAddress target = new MacAddress(bytes);
            Assert.IsTrue(result.ContainsKey(target));
        }
Esempio n. 6
0
 public override void OnStart(Router router, System.Collections.Generic.Dictionary <string, object> args)
 {
     if (!args?.ContainsKey("score") ?? true)
     {
         Root.Add(new TextDrawable("譜面がありません", new Font(FontFamily.GenericSansSerif, 64)));
         return;
     }
     score             = args["score"] as Score;
     router.Game.Title = $"{score.Title} - {score.Artist}  {Helper.CreateDifficulty(score.Difficulty, score.Level)}";
     player.Play(score.Source);
 }
Esempio n. 7
0
        public static string GetGoRoot()
        {
            System.Collections.Generic.Dictionary<string, string> dict =
                new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.InvariantCultureIgnoreCase);
            dict.Add("COR-W81-101", @"D:\Programme\Go\");

            if (dict.ContainsKey(System.Environment.MachineName))
                return dict[System.Environment.MachineName];

            string goroot = System.Environment.GetEnvironmentVariable("goroot");

            if (!string.IsNullOrEmpty(goroot))
                return goroot;

            throw new System.NotSupportedException("You need to configure the goroot environment variable");
        }
Esempio n. 8
0
 public void CancelOrderExpr(string expr)
 {
     try
     {
         System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<int>> dictionary = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<int>>();
         if (!string.IsNullOrWhiteSpace(expr))
         {
             DataView dataView = new DataView(Game.State.OpenOrderView.Table, Game.State.OpenOrderView.RowFilter, "", Game.State.OpenOrderView.RowStateFilter);
             dataView.RowFilter = string.Concat(new string[]
             {
                 "(",
                 dataView.RowFilter,
                 ") AND (",
                 expr,
                 ")"
             });
             foreach (DataRowView dataRowView in dataView)
             {
                 string key = (string)dataRowView["Ticker"];
                 if (!dictionary.ContainsKey(key))
                 {
                     dictionary.Add(key, new System.Collections.Generic.List<int>());
                 }
                 dictionary[key].Add((int)dataRowView["ID"]);
             }
             foreach (System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.List<int>> current in dictionary)
             {
                 try
                 {
                     System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.List<int>> k = current;
                     ServiceManager.Execute(delegate(IClientService p)
                     {
                         p.CancelOrder(k.Key, k.Value.ToArray());
                     });
                 }
                 catch (FaultException)
                 {
                 }
             }
         }
     }
     catch
     {
     }
 }
        /// <summary>
        /// 得到出货单dto
        /// </summary>
        /// <param name="bpObj"></param>
        /// <returns></returns>
        private System.Collections.Generic.List<UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData> GetShipDTOList(System.Collections.Generic.List<CarShipLineDTO> shiplist)
        {
            System.Collections.Generic.List<UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData> list = new System.Collections.Generic.List<UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData>();
            //string opeatorstr = "DMSTESTUSER";
            //string opeatorstr = "DMS";
            string opeatorstr = HBHCommon.DefaultShipOperatorCode;
            System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<CarShipLineDTO>> dic = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<CarShipLineDTO>>();
            foreach (CarShipLineDTO dtoline in shiplist)
            {
                if (!dic.ContainsKey(dtoline.SpitOrderFlag))
                {
                    dic.Add(dtoline.SpitOrderFlag, new System.Collections.Generic.List<CarShipLineDTO>());
                }
                dic[dtoline.SpitOrderFlag].Add(dtoline);
            }
            foreach (string key in dic.Keys)
            {
                List<CarShipLineDTO> listLineDTO = dic[key];

                if (listLineDTO != null
                    && listLineDTO.Count > 0
                    )
                {
                    CarShipLineDTO firstDTO = listLineDTO.GetFirst<CarShipLineDTO>();

                    UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData shipdto = new UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData();
                    shipdto.CreatedBy = (Context.LoginUser);
                    shipdto.ModifiedBy = (Context.LoginUser);
                    string doctypecode = string.Empty;
                    shipdto.DocumentType = (new CommonArchiveDataDTOData());
                    if (firstDTO.OrderType == 401103 && firstDTO.IsSale)
                    {
                        doctypecode = "XM7";
                    }
                    else if (firstDTO.VehicleOrChassis == 400102)
                    {
                        doctypecode = "XM4";
                    }
                    else
                    {
                        doctypecode = "XM1";
                    }
                    shipdto.DocumentType.Code = (doctypecode);
                    long ConfirmAccording = -1L;
                    int ConfirmMode = -1;
                    long ConfirmTerm = -1L;
                    long InvoiceAccording = -1L;
                    long ReceivableTerm = -1L;
                    ShipDocType doctype = ShipDocType.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), doctypecode), new OqlParam[0]);
                    if (doctype != null)
                    {
                        if (doctype.ConfirmAccordingKey != null)
                        {
                            ConfirmAccording = doctype.ConfirmAccordingKey.ID;
                        }
                        if (doctype.ConfirmMode.Value >= 0)
                        {
                            ConfirmMode = doctype.ConfirmMode.Value;
                        }
                        if (doctype.InvoiceAccordingKey != null)
                        {
                            InvoiceAccording = doctype.InvoiceAccordingKey.ID;
                        }
                    }
                    Customer customer = Customer.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), firstDTO.DealerCode), new OqlParam[0]);
                    if (customer != null)
                    {
                        if (customer.ARConfirmTermKey != null)
                        {
                            ConfirmTerm = customer.ARConfirmTermKey.ID;
                        }
                        if (customer.RecervalTermKey != null)
                        {
                            ReceivableTerm = customer.RecervalTermKey.ID;
                        }
                        shipdto.BargainMode = (customer.Bargain.Value);
                        shipdto.ShipmentRule = (new CommonArchiveDataDTOData());
                        if (customer.ShippmentRule != null)
                        {
                            shipdto.ShipmentRule.Code = (customer.ShippmentRule.Code);
                        }
                        else
                        {
                            shipdto.ShipmentRule.Code = ("C001");
                        }
                        if (customer.RecervalTerm != null)
                        {
                            string RecTerm = customer.RecervalTerm.Code;
                        }
                    }
                    else
                    {
                        shipdto.ShipmentRule.Code = ("C001");
                        shipdto.BargainMode = (0);
                    }
                    shipdto.SrcDocType = (0);
                    shipdto.ReceivableTerm = (new CommonArchiveDataDTOData());
                    if (ReceivableTerm > 0L)
                    {
                        shipdto.ReceivableTerm.ID = (ReceivableTerm);
                    }
                    else
                    {
                        shipdto.ReceivableTerm.Code = ("01");
                    }
                    shipdto.ConfirmTerm = (new CommonArchiveDataDTOData());
                    if (ConfirmTerm > 0L)
                    {
                        shipdto.ConfirmTerm.ID = (ConfirmTerm);
                    }
                    else
                    {
                        shipdto.ConfirmTerm.Code = ("01");
                    }
                    shipdto.ConfirmAccording = (new CommonArchiveDataDTOData());
                    shipdto.ConfirmAccording.ID = (ConfirmAccording);
                    shipdto.ConfirmMode = ((ConfirmMode < 0) ? 0 : ConfirmMode);
                    shipdto.InvoiceAccording = (new CommonArchiveDataDTOData());
                    shipdto.InvoiceAccording.ID = (InvoiceAccording);
                    shipdto.Seller = (new CommonArchiveDataDTOData());
                    shipdto.Seller.Code = (opeatorstr);
                    Operators opeator = Operators.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), opeatorstr), new OqlParam[0]);
                    if (opeator != null)
                    {
                        shipdto.SaleDept = (new CommonArchiveDataDTOData());
                        shipdto.SaleDept.ID = (opeator.DeptKey.ID);
                    }
                    shipdto.CreatedBy = (Context.LoginUser);
                    shipdto.CreatedOn = (System.DateTime.Now);
                    shipdto.OrderBy = (new CommonArchiveDataDTOData());
                    shipdto.OrderBy.Code = (firstDTO.DealerCode);
                    shipdto.AC = (new CommonArchiveDataDTOData());
                    shipdto.AC.Code = (string.IsNullOrEmpty(firstDTO.Currency) ? "C001" : firstDTO.Currency);
                    shipdto.TC = (new CommonArchiveDataDTOData());
                    shipdto.TC.Code = (string.IsNullOrEmpty(firstDTO.Currency) ? "C001" : firstDTO.Currency);
                    shipdto.DescFlexField = (new DescFlexSegmentsData());
                    shipdto.DescFlexField.PubDescSeg5 = (firstDTO.DmsSaleNo);
                    shipdto.DescFlexField.PrivateDescSeg1 = (firstDTO.DMSShipNo);
                    System.DateTime arg_5CD_0 = firstDTO.ShipDate;
                    if (firstDTO.ShipDate != System.DateTime.MinValue && firstDTO.ShipDate > System.DateTime.Now)
                    {
                        shipdto.BusinessDate = (firstDTO.ShipDate);
                    }
                    else
                    {
                        shipdto.BusinessDate = (System.DateTime.Now);
                    }
                    shipdto.ShipLines = (new System.Collections.Generic.List<UFIDA.U9.ISV.SM.ShipLineDTOForIndustryChainData>());
                    foreach (CarShipLineDTO linedto in listLineDTO)
                    {
                        UFIDA.U9.ISV.SM.ShipLineDTOForIndustryChainData shiplinedto = new UFIDA.U9.ISV.SM.ShipLineDTOForIndustryChainData();
                        shiplinedto.ItemInfo = (new ItemInfoData());
                        shiplinedto.ItemInfo.ItemCode = (linedto.ErpMaterialCode);
                        shiplinedto.ShipQtyTUAmount = (linedto.Number);
                        shiplinedto.TotalMoneyTC = (linedto.Money);
                        shiplinedto.TotalNetMoneyTC = (linedto.Money);
                        shiplinedto.Project = (new CommonArchiveDataDTOData());
                        shiplinedto.Project.Code = (linedto.DmsSaleNo);
                        shiplinedto.ConfirmAccording = (new CommonArchiveDataDTOData());
                        shiplinedto.ConfirmAccording.ID = (ConfirmAccording);
                        shiplinedto.ConfirmMode = ((ConfirmMode < 0) ? 0 : ConfirmMode);
                        shiplinedto.ConfirmTerm = (new CommonArchiveDataDTOData());
                        if (ConfirmTerm > 0L)
                        {
                            shiplinedto.ConfirmTerm.ID = (ConfirmTerm);
                        }
                        else
                        {
                            shiplinedto.ConfirmTerm.Code = ("01");
                        }
                        shiplinedto.InvoiceAccording = (new CommonArchiveDataDTOData());
                        shiplinedto.InvoiceAccording.ID = (InvoiceAccording);
                        shiplinedto.ReceivableTerm = (new CommonArchiveDataDTOData());
                        if (ReceivableTerm > 0L)
                        {
                            shiplinedto.ReceivableTerm.ID = (ReceivableTerm);
                        }
                        else
                        {
                            shiplinedto.ReceivableTerm.Code = ("01");
                        }
                        shiplinedto.WH = (new CommonArchiveDataDTOData());
                        string whcode = string.Empty;
                        /*  OrderType
                        401102;//预测订单
                        401101;//追加订单
                        401103;//监控车订单
                        401104;//储备订单
                         */
                        /*
                        0080	储运整车库
                        0081	储运车库2
                        0090	储运二类底盘库
                         */
                        /*
                        是不是 监控车订单,从 储运车库2 (0081) 发车;
            底盘,从 储运二类底盘库 (0090) 发车;
            其他订单,从  储运整车库 (0080) 发车?
                         */
                        if (firstDTO.OrderType == 401103 && firstDTO.IsSale)
                        {
                            whcode = "0081";
                        }
                        else if (firstDTO.VehicleOrChassis == 400102)
                        {
                            whcode = "0090";
                        }
                        else
                        {
                            whcode = "0080";
                        }
                        shiplinedto.WH.Code = (whcode);
                        Warehouse whout = Warehouse.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), whcode), new OqlParam[0]);
                        if (whout != null && whout.DepositType == DepositTypeEnum.VMI)
                        {
                            shiplinedto.VMI = (true);
                            //shiplinedto.VMI = whout.DepositType == DepositTypeEnum.VMI;
                            if (whout.Supplier != null)
                            {
                                shiplinedto.Supplier = (new CommonArchiveDataDTOData());
                                shiplinedto.Supplier.Code = (whout.Supplier.Code);
                            }
                        }
                        shiplinedto.DescFlexField = (new DescFlexSegmentsData());
                        shiplinedto.DescFlexField.PubDescSeg5 = (linedto.DmsSaleNo);
                        shiplinedto.Project = (new CommonArchiveDataDTOData());
                        shiplinedto.Project.Code = (linedto.DmsSaleNo);
                        shiplinedto.DescFlexField.PubDescSeg13 = (linedto.EarnestMoney.ToString());
                        shiplinedto.DescFlexField.PubDescSeg14 = ((linedto.ShipMoney <= 0m) ? (linedto.Money - linedto.EarnestMoney).ToString() : linedto.ShipMoney.ToString());
                        shiplinedto.DescFlexField.PubDescSeg21 = (linedto.Deposit.ToString());
                        shiplinedto.DescFlexField.PubDescSeg12 = (linedto.VIN);
                        shipdto.ShipLines.Add(shiplinedto);
                    }
                    list.Add(shipdto);
                }
            }
            return list;
        }
Esempio n. 10
0
        /// <summary> We're going to examine rows from the middle outward, searching alternately above and below the
        /// middle, and farther out each time. rowStep is the number of rows between each successive
        /// attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
        /// middle + rowStep, then middle - (2 * rowStep), etc.
        /// rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
        /// decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
        /// image if "trying harder".
        ///
        /// </summary>
        /// <param name="image">The image to decode
        /// </param>
        /// <param name="hints">Any hints that were requested
        /// </param>
        /// <returns> The contents of the decoded barcode
        /// </returns>
        /// <throws>  ReaderException Any spontaneous errors which occur </throws>
        // private Result doDecode(BinaryBitmap image, System.Collections.Hashtable hints) // commented by .net follower (http://dotnetfollower.com)
        private Result doDecode(BinaryBitmap image, System.Collections.Generic.Dictionary <Object, Object> hints) // added by .net follower (http://dotnetfollower.com)
        {
            int      width  = image.Width;
            int      height = image.Height;
            BitArray row    = new BitArray(width);

            int  middle    = height >> 1;
            bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
            int  rowStep   = System.Math.Max(1, height >> (tryHarder?7:4));
            int  maxLines;

            if (tryHarder)
            {
                maxLines = height;                 // Look at the whole image, not just the center
            }
            else
            {
                maxLines = 9;                 // Nine rows spaced 1/16 apart is roughly the middle half of the image
            }

            for (int x = 0; x < maxLines; x++)
            {
                // Scanning from the middle out. Determine which row we're looking at next:
                int  rowStepsAboveOrBelow = (x + 1) >> 1;
                bool isAbove   = (x & 0x01) == 0;               // i.e. is x even?
                int  rowNumber = middle + rowStep * (isAbove?rowStepsAboveOrBelow:-rowStepsAboveOrBelow);
                if (rowNumber < 0 || rowNumber >= height)
                {
                    // Oops, if we run off the top or bottom, stop
                    break;
                }

                // Estimate black point for this row and load it:
                try
                {
                    row = image.getBlackRow(rowNumber, row);
                }
                catch (ReaderException re)
                {
                    continue;
                }

                // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
                // handle decoding upside down barcodes.
                for (int attempt = 0; attempt < 2; attempt++)
                {
                    if (attempt == 1)
                    {
                        // trying again?
                        row.reverse();                         // reverse the row and continue
                        // This means we will only ever draw result points *once* in the life of this method
                        // since we want to avoid drawing the wrong points after flipping the row, and,
                        // don't want to clutter with noise from every single row scan -- just the scans
                        // that start on the center line.
                        if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
                        {
                            // System.Collections.Hashtable newHints = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); // Can't use clone() in J2ME // commented by .net follower (http://dotnetfollower.com)
                            System.Collections.Generic.Dictionary <Object, Object> newHints = new System.Collections.Generic.Dictionary <Object, Object>(); // Can't use clone() in J2ME // added by .net follower (http://dotnetfollower.com)
                            System.Collections.IEnumerator hintEnum = hints.Keys.GetEnumerator();
                            //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
                            while (hintEnum.MoveNext())
                            {
                                //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
                                System.Object key = hintEnum.Current;
                                if (!key.Equals(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
                                {
                                    newHints[key] = hints[key];
                                }
                            }
                            hints = newHints;
                        }
                    }
                    try
                    {
                        // Look for a barcode
                        Result result = decodeRow(rowNumber, row, hints);
                        // We found our barcode
                        if (attempt == 1)
                        {
                            // But it was upside down, so note that
                            result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) 180);
                            // And remember to flip the result points horizontally.
                            ResultPoint[] points = result.ResultPoints;
                            points[0] = new ResultPoint(width - points[0].X - 1, points[0].Y);
                            points[1] = new ResultPoint(width - points[1].X - 1, points[1].Y);
                        }
                        return(result);
                    }
                    catch (ReaderException re)
                    {
                        // continue -- just couldn't decode this row
                    }
                }
            }

            throw ReaderException.Instance;
        }
        private void LoadFontTextures()
        {
            for (int i = 0; i < font.PageTexPaths.Length; i++)
            {
                if (font.PageTexPaths[i] == null)
                {
                    continue;
                }

                string texkey  = font.PageTexPaths[i];
                string texpath = font.PageTexPaths[i];

                try
                {
                    if (font.CanLoad8Bit)
                    {
                        if (!textures.ContainsKey(texkey))
                        {
                            textures.Add(texkey, OpenTkTextureLoadFuncs.LoadTexture8BitGrayscale(texpath));
                        }
                        else
                        {
                            textures[texkey] = OpenTkTextureLoadFuncs.LoadTexture8BitGrayscale(texpath);
                        }
                    }
                    else if (!font.CommonInfo.Packed | !font.AreAllGylphsSingleChannel) // if not packed, should always load normally.
                                                                                        // if packed but some glyphs use multiple channels, should load a normal copy too
                    {
                        if (!textures.ContainsKey(texkey))
                        {
                            textures.Add(texkey, OpenTkTextureLoadFuncs.LoadTexture(texpath));
                        }
                        else
                        {
                            textures[texkey] = OpenTkTextureLoadFuncs.LoadTexture(texpath);
                        }
                    }

                    if (font.CommonInfo.Packed)
                    {
                        int[] channelTextures = OpenTkTextureLoadFuncs.LoadTextureToSplitChannels(texpath);

                        if (channelTextures.Length < 4)
                        {
                            throw new Exception("not enough channels in image");
                        }

                        if (!textures.ContainsKey(texkey + "A"))
                        {
                            textures.Add(texkey + "A", channelTextures[0]);
                        }
                        else
                        {
                            textures[texkey + "A"] = channelTextures[0];
                        }

                        if (!textures.ContainsKey(texkey + "R"))
                        {
                            textures.Add(texkey + "R", channelTextures[1]);
                        }
                        else
                        {
                            textures[texkey + "R"] = channelTextures[1];
                        }

                        if (!textures.ContainsKey(texkey + "G"))
                        {
                            textures.Add(texkey + "G", channelTextures[2]);
                        }
                        else
                        {
                            textures[texkey + "G"] = channelTextures[2];
                        }

                        if (!textures.ContainsKey(texkey + "B"))
                        {
                            textures.Add(texkey + "B", channelTextures[3]);
                        }
                        else
                        {
                            textures[texkey + "B"] = channelTextures[3];
                        }
                    }
                }
                catch (Exception e)
                {
                    SkinnedMessageBox.Show(ErrorSkin, DialogResMgr.GetString("MissingTextureError") + "\n(" + texpath + ")", "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    throw e;
                }
            }
        }
        /// <summary>
        /// Updates the child object.
        /// </summary>
        /// <param name="parameters">The parameters collection may contain more parameters than needed based on the context it was called. We need to filter this list.</param>
        protected override void Child_Update(params object[] parameters)
        {
            bool cancel = false;
            OnUpdating(ref cancel);
            if (cancel) return;

            // We require that one of the parameters be a connection so we can do the CRUD operations.
            var connection = parameters.OfType<SqlConnection>().FirstOrDefault();
            if (connection == null)
                throw new ArgumentNullException("parameters", "Must contain a SqlConnection parameter.");

            RaiseListChangedEvents = false;

            foreach (var item in DeletedList)
            {
                DataPortal.UpdateChild(item, connection);
            }

            DeletedList.Clear();
            
            // Trim down the list to what is actually contained in the child class.
            var list = new System.Collections.Generic.Dictionary<string, object>() {};
            foreach (object o in parameters)
            {
                if(o == null) continue;

                var key = o.GetType().ToString();
                if (!list.ContainsKey(key))
                    list.Add(key, o);
            }

            foreach (var item in Items)
            {
                DataPortal.UpdateChild(item, list.Values.ToArray());
            }

            RaiseListChangedEvents = true;

            OnUpdated();
        }
Esempio n. 13
0
        // 得到调入单dto
        /// <summary>
        /// 得到调入单dto
        /// </summary>
        /// <param name="bpObj"></param>
        /// <returns></returns>
        private System.Collections.Generic.List<UFIDA.U9.ISV.SM.RMADTOData> GetRMADTOList(CreateRMASV bpObj)
        {
            System.Collections.Generic.List<UFIDA.U9.ISV.SM.RMADTOData> list = new System.Collections.Generic.List<UFIDA.U9.ISV.SM.RMADTOData>();
            System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<RMALineDTO>> dic = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<RMALineDTO>>();
            foreach (RMALineDTO dtoline in bpObj.RMALineDTOs)
            {
                if (!dic.ContainsKey(dtoline.SpitOrderFlag))
                {
                    dic.Add(dtoline.SpitOrderFlag, new System.Collections.Generic.List<RMALineDTO>());
                }
                dic[dtoline.SpitOrderFlag].Add(dtoline);
            }
            foreach (string key in dic.Keys)
            {
                List<RMALineDTO> listLineDTO = dic[key];

                if (listLineDTO != null
                    && listLineDTO.Count > 0
                    )
                {
                    RMALineDTO firstDTO = listLineDTO.GetFirst<RMALineDTO>();

                    UFIDA.U9.ISV.SM.RMADTOData rmadto = new UFIDA.U9.ISV.SM.RMADTOData();
                    RMALineDTO dto = firstDTO;
                    rmadto.DocumentTypeDTO = (new IDCodeNameDTOData());
                    rmadto.DocumentTypeDTO.Code = ("H0001");
                    rmadto.KeepAccountsPeriodDTO = (new IDCodeNameDTOData());
                    RMADocType doctype = RMADocType.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), "H0001"), new OqlParam[0]);
                    if (doctype != null)
                    {
                        if (doctype.AccountAccordingKey != null)
                        {
                            rmadto.ConfirmAccordingDTO = (new IDCodeNameDTOData());
                            rmadto.ConfirmAccordingDTO.Code = (doctype.AccountAccording.Code);
                        }
                        if (doctype.BillingMode.Value >= 0)
                        {
                            rmadto.BillingMode = (doctype.BillingMode.Value);
                        }
                        else
                        {
                            rmadto.BillingMode = (0);
                        }
                        if (doctype.InvoiceAccordingKey != null)
                        {
                            rmadto.InvoiceAccordingDTO = (new IDCodeNameDTOData());
                            rmadto.InvoiceAccordingDTO.Code = (doctype.InvoiceAccording.Code);
                        }
                    }
                    else
                    {
                        rmadto.BillingMode = (0);
                    }
                    rmadto.AccrueTermDTO = (new IDCodeNameDTOData());
                    rmadto.AccrueTermDTO.Code = ("01");
                    rmadto.CustomerDTO = (new IDCodeNameDTOData());
                    rmadto.CustomerDTO.Code = (dto.DealerCode);
                    rmadto.ACDTO = (new IDCodeNameDTOData());
                    rmadto.ACDTO.Code = (string.IsNullOrEmpty(dto.Currency) ? "C001" : dto.Currency);
                    rmadto.TCDTO = (new IDCodeNameDTOData());
                    rmadto.TCDTO.Code = (string.IsNullOrEmpty(dto.Currency) ? "C001" : dto.Currency);
                    rmadto.DescFlexField = (new DescFlexSegmentsData());
                    rmadto.DescFlexField.PubDescSeg5 = (dto.DmsSaleNo);
                    rmadto.DescFlexField.PrivateDescSeg1 = (dto.DMSShipNo);
                    rmadto.DescFlexField.PubDescSeg12 = (dto.VIN);
                    rmadto.DescFlexField.PubDescSeg13 = (dto.EarnestMoney.ToString());
                    rmadto.DescFlexField.PubDescSeg14 = ((dto.ShipMoney <= 0m) ? (dto.Money - dto.EarnestMoney).ToString() : dto.ShipMoney.ToString());
                    rmadto.DescFlexField.PubDescSeg21 = (dto.Deposit.ToString());
                    System.DateTime arg_354_0 = dto.ShipDate;
                    if (dto.ShipDate != System.DateTime.MinValue && dto.ShipDate > System.DateTime.Now)
                    {
                        rmadto.BusinessDate = (dto.ShipDate);
                    }
                    else
                    {
                        rmadto.BusinessDate = (System.DateTime.Now);
                    }
                    rmadto.RMALines = (new System.Collections.Generic.List<ISV.SM.RMALineDTOData>());
                    foreach (RMALineDTO linedto in listLineDTO)
                    {
                        ISV.SM.RMALineDTOData rmalinedto = new ISV.SM.RMALineDTOData();
                        rmalinedto.ItemInfoDTO = (new IDCodeNameDTOData());
                        rmalinedto.ItemInfoDTO.Code = (linedto.ErpMaterialCode);
                        rmalinedto.ApplyQtyTU1 = (linedto.Number);
                        rmalinedto.RtnQtyTU1 = (linedto.Number);
                        rmalinedto.RtnQtyPU = (linedto.Number);
                        rmalinedto.ApplyMoneyTC = (linedto.Money);
                        rmalinedto.ApplyNetMoneyTC = (linedto.Money);
                        rmalinedto.ProjectDTO = (new IDCodeNameDTOData());
                        rmalinedto.ProjectDTO.Code = (linedto.DmsSaleNo);
                        rmalinedto.WarehouseDTO = (new IDCodeNameDTOData());
                        rmalinedto.WarehouseDTO.Code = (linedto.WHIn);
                        rmadto.RMALines.Add(rmalinedto);
                    }
                    list.Add(rmadto);
                }
            }
            return list;
        }
Esempio n. 14
0
        /// <summary>The subSpans are ordered in the same doc, so there is a possible match.
        /// Compute the slop while making the match as short as possible by advancing
        /// all subSpans except the last one in reverse order.
        /// </summary>
        private bool ShrinkToAfterShortestMatch()
        {
            matchStart = subSpans[subSpans.Length - 1].Start();
            matchEnd   = subSpans[subSpans.Length - 1].End();
            System.Collections.Generic.Dictionary <byte[], byte[]> possibleMatchPayloads = new System.Collections.Generic.Dictionary <byte[], byte[]>();
            if (subSpans[subSpans.Length - 1].IsPayloadAvailable())
            {
                System.Collections.Generic.ICollection <byte[]> payload = subSpans[subSpans.Length - 1].GetPayload();
                foreach (byte[] pl in payload)
                {
                    if (!possibleMatchPayloads.ContainsKey(pl))
                    {
                        possibleMatchPayloads.Add(pl, pl);
                    }
                }
            }

            System.Collections.Generic.List <byte[]> possiblePayload = null;

            int matchSlop = 0;
            int lastStart = matchStart;
            int lastEnd   = matchEnd;

            for (int i = subSpans.Length - 2; i >= 0; i--)
            {
                Spans prevSpans = subSpans[i];
                if (collectPayloads && prevSpans.IsPayloadAvailable())
                {
                    System.Collections.Generic.ICollection <byte[]> payload = prevSpans.GetPayload();
                    possiblePayload = new System.Collections.Generic.List <byte[]>(payload.Count);
                    possiblePayload.AddRange(payload);
                }

                int prevStart = prevSpans.Start();
                int prevEnd   = prevSpans.End();
                while (true)
                {
                    // Advance prevSpans until after (lastStart, lastEnd)
                    if (!prevSpans.Next())
                    {
                        inSameDoc = false;
                        more      = false;
                        break;                         // Check remaining subSpans for final match.
                    }
                    else if (matchDoc != prevSpans.Doc())
                    {
                        inSameDoc = false;             // The last subSpans is not advanced here.
                        break;                         // Check remaining subSpans for last match in this document.
                    }
                    else
                    {
                        int ppStart = prevSpans.Start();
                        int ppEnd   = prevSpans.End();                       // Cannot avoid invoking .end()
                        if (!DocSpansOrdered(ppStart, ppEnd, lastStart, lastEnd))
                        {
                            break;                             // Check remaining subSpans.
                        }
                        else
                        {
                            // prevSpans still before (lastStart, lastEnd)
                            prevStart = ppStart;
                            prevEnd   = ppEnd;
                            if (collectPayloads && prevSpans.IsPayloadAvailable())
                            {
                                System.Collections.Generic.ICollection <byte[]> payload = prevSpans.GetPayload();
                                possiblePayload = new System.Collections.Generic.List <byte[]>(payload.Count);
                                possiblePayload.AddRange(payload);
                            }
                        }
                    }
                }

                if (collectPayloads && possiblePayload != null)
                {
                    foreach (byte[] pl in possiblePayload)
                    {
                        if (!possibleMatchPayloads.ContainsKey(pl))
                        {
                            possibleMatchPayloads.Add(pl, pl);
                        }
                    }
                }

                System.Diagnostics.Debug.Assert(prevStart <= matchStart);
                if (matchStart > prevEnd)
                {
                    // Only non overlapping spans add to slop.
                    matchSlop += (matchStart - prevEnd);
                }

                /* Do not break on (matchSlop > allowedSlop) here to make sure
                 * that subSpans[0] is advanced after the match, if any.
                 */
                matchStart = prevStart;
                lastStart  = prevStart;
                lastEnd    = prevEnd;
            }

            bool match = matchSlop <= allowedSlop;

            if (collectPayloads && match && possibleMatchPayloads.Count > 0)
            {
                matchPayload.AddRange(possibleMatchPayloads.Keys);
            }

            return(match);            // ordered and allowed slop
        }
 private System.Collections.Generic.Dictionary<string, Val> ProcessDict()
 {
     var dictionary = new System.Collections.Generic.Dictionary<string, Val>();
     while (_torrent.PeekChar() != 0x65)
     {
         string key = ProcessString();
         if (key == "info")
         {
             _infoStart = _torrent.BaseStream.Position;
         }
         if (key == "pieces")
         {
             dictionary.Add(key, ProcessByte());
         }
         else
         {
             Val val = ProcessVal();
             if (!dictionary.ContainsKey(key))
                 dictionary.Add(key, val);
         }
         if (key == "info")
         {
             _infoEnd = _torrent.BaseStream.Position - _infoStart;
         }
     }
     _torrent.Read();
     return dictionary;
 }
Esempio n. 16
0
 public bool Has(SessionID sessionID)
 {
     return(settings_.ContainsKey(sessionID));
 }
Esempio n. 17
0
        public void PreLoadStepFile(string pNumber, int open)
        {
            if (!fileList.ContainsKey(pNumber))
            {
                fileList.Add(pNumber, "initialized");

                string savingDirectory = Properties.Settings.Default.projectFolder;
                foreach (string s in System.IO.Directory.GetFiles(savingDirectory))
                {
                    if (s.Substring(savingDirectory.Length)
                        .Contains(pNumber))
                    {
                        if (s.Contains(".ipt"))
                        {
                            fileList[pNumber] = "exists:" + s;
                            return;
                        }
                    }
                }

                //Load Offscreen browser to partNumber webpage, to extract file locations
                int    tries    = 0;
                string fileName = "";
retry:
                if (tries < 3)
                {
                    string url = urlBase + pNumber;
                    _headlessBrowser.OpenUrl(url);
                    var tS = _headlessBrowser.Page.EvaluateScriptAsync(@"var a = 'empty';for (let i of document.getElementsByClassName('li--cad')){if (i.dataset.mcmCadOption.includes('STEP')){a = i.dataset.mcmCadOption;}} a;");
                    tS.Wait();
                    JavascriptResponse response = tS.Result;
                    var result = response.Success ? (response.Result ?? "null") : response.Message;
                    fileName = (string)result;
                    if (!fileName.Contains(pNumber))
                    {
                        tries++;
                        System.Threading.Thread.Sleep(500);
                        goto retry;
                    }
                    else
                    {
                        fileList[pNumber] = urlBase + fileName.Substring(1);
                        System.Diagnostics.Debug.WriteLine("url: " + fileName);
                        fileName = ReverseString(fileName);
                        fileName = ReverseString(fileName.Substring(0, fileName.IndexOf('/')));
                        System.Diagnostics.Debug.WriteLine("good to go: " + fileName);
                        if (Directory.Exists(savingDirectory))
                        {
                            using (var client = new System.Net.WebClient())
                            {
                                string filePath = System.IO.Path.Combine(savingDirectory, fileName);//Saving Directory for .step temp file
                                System.Diagnostics.Debug.WriteLine(filePath);
                                System.Net.ServicePointManager.SecurityProtocol =
                                    System.Net.SecurityProtocolType.Tls |
                                    System.Net.SecurityProtocolType.Tls11 |
                                    System.Net.SecurityProtocolType.Tls12;
                                fileList[pNumber] = "beginDownload:" + fileList[pNumber];
                                client.DownloadFile(new System.Uri(fileList[pNumber]
                                                                   .Substring("beginDownload:".Length)), filePath);
                                fileList[pNumber] = "isDownloaded:" + fileName.Length.ToString("X4") + filePath;
                                fileList[pNumber] = "exists:" + m_Importer.Translate(fileList[pNumber]
                                                                                     .Substring("isDownloaded:".Length));
                                if (open != 0)
                                {
                                    bool isAssembly = true;
                                    if (open == 2)
                                    {
                                        isAssembly = false;
                                    }
                                    m_Importer.Open(fileList[pNumber]
                                                    .Substring("exists:".Length), isAssembly);
                                }
                            }
                        }
                    }
                }
                else
                {
                    fileList.Remove(pNumber);
                    MessageBox.Show("Couldn't retrieve " + pNumber);
                }
            }
        }
Esempio n. 18
0
		// TODO: Remove warning after API has been finalized
		/// <summary> WARNING: The List is not necessarily in order of the the positions</summary>
		/// <returns> Collection of <code>byte[]</code> payloads
		/// </returns>
		/// <throws>  IOException </throws>
		public override System.Collections.Generic.ICollection<byte[]> GetPayload()
		{
            //mgarski: faking out another HashSet<T>...
			System.Collections.Generic.Dictionary<byte[], byte[]> matchPayload = new System.Collections.Generic.Dictionary<byte[], byte[]>(); 
			for (SpansCell cell = first; cell != null; cell = cell.next)
			{
				if (cell.IsPayloadAvailable())
				{
                    System.Collections.Generic.ICollection<byte[]> cellPayload = cell.GetPayload();
                    foreach (byte[] val in cellPayload)
                    {
                        if (!matchPayload.ContainsKey(val))
                        {
                            matchPayload.Add(val, val);
                        }
                    }
				}
			}
			return matchPayload.Keys;
		}
Esempio n. 19
0
        void ExportCsv(string in_path, System.Collections.Generic.IEnumerable<Google.GData.Spreadsheets.WorksheetEntry> in_entries, bool in_bSanitize)
        {
            ShowNotification(new GUIContent("Saving to: " + in_path));
            Debug.Log("Saving to: " + in_path);

            // System.Collections.Generic.Dictionary< String Key, System.Collections.Generic.Dictionary< Language, String Value > >
            var allRows = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>>();
            var colHeaders = new System.Collections.Generic.List<string>();
            // for each page


            foreach (var listFeed in in_entries.Select(in_entry => in_entry.Links.FindService(Google.GData.Spreadsheets.GDataSpreadsheetsNameTable.ListRel, null)).Select(in_listFeedLink => new Google.GData.Spreadsheets.ListQuery(in_listFeedLink.HRef.ToString())).Select(in_listQuery => _Service.Query(in_listQuery)).Where(in_listFeed => in_listFeed.Entries.Count > 0))
            {
                var curCol = 0;
                // Iterate through each row, printing its cell values.
                foreach (var atomEntry in listFeed.Entries)
                {
                    var row = (Google.GData.Spreadsheets.ListEntry)atomEntry;
                    // Don't process rows marked for _Ignore
                    if (GfuStrCmp(row.Title.Text, "VOID"))
                    {
                        continue;
                    }

                    // Iterate over the columns, and print each cell value
                    foreach (Google.GData.Spreadsheets.ListEntry.Custom element in row.Elements)
                    {
                        // Don't process columns marked for _Ignore
                        if (GfuStrCmp(element.LocalName, "VOID"))
                        {
                            curCol++;
                            continue;
                        }

                        if (curCol > 0)
                        {
                            if (!allRows.ContainsKey(row.Title.Text))
                                allRows.Add(row.Title.Text, new System.Collections.Generic.Dictionary<string, string>());
                            allRows[row.Title.Text].Add(element.LocalName, element.Value);

                            // Maintain a single list of available column headers, we will use this to
                            // iterate the columns later
                            if (!colHeaders.Contains(element.LocalName))
                                colHeaders.Add(element.LocalName);
                        }
                        curCol++;
                    }

                    curCol = 0;
                }
            }

            var fs = System.IO.File.Open(in_path, System.IO.File.Exists(in_path) ? System.IO.FileMode.Truncate : System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);

            var sw = new System.IO.StreamWriter(fs);
            string fileString = "KEY,";

            foreach (var colHeader in colHeaders)
            {
                fileString += colHeader;
                if (colHeader != colHeaders[colHeaders.Count - 1])
                    fileString += ",";
            }
            fileString += System.Environment.NewLine;

            foreach (var curRow in allRows)
            {

                fileString += curRow.Key + ",";
                System.Collections.Generic.Dictionary<string, string> rowValue = curRow.Value;

                foreach (string colHeader in colHeaders)
                {
                    if (rowValue.ContainsKey(colHeader))
                    {
                        if (in_bSanitize)
                            fileString += SanitizeDf(rowValue[colHeader]);
                        else
                            fileString += rowValue[colHeader];
                    }
                    if (colHeader != colHeaders[colHeaders.Count - 1])
                        fileString += ",";
                }
                fileString += System.Environment.NewLine;
            }

            sw.Write(fileString);
            sw.Close();

            fs.Close();
        }
Esempio n. 20
0
        void ExportNguiLegacy(string in_path, System.Collections.Generic.IEnumerable<Google.GData.Spreadsheets.WorksheetEntry> in_entries)
        {
            if (_FoundNgui == false)
                return;

            ShowNotification(new GUIContent("Saving to: " + in_path));
            Debug.Log("Saving to: " + in_path);

            var languages = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>>();

            // for each page
            foreach (Google.GData.Spreadsheets.WorksheetEntry entry in in_entries)
            {
                // Define the URL to request the list feed of the worksheet.
                var listFeedLink = entry.Links.FindService(Google.GData.Spreadsheets.GDataSpreadsheetsNameTable.ListRel, null);

                // Fetch the list feed of the worksheet.
                var listQuery = new Google.GData.Spreadsheets.ListQuery(listFeedLink.HRef.ToString());
                var listFeed = _Service.Query(listQuery);

                var curCol = 0;
                if (listFeed.Entries.Count <= 0) continue;

                foreach (var atomEntry in listFeed.Entries)
                {
                    var row = (Google.GData.Spreadsheets.ListEntry)atomEntry;

                    foreach (Google.GData.Spreadsheets.ListEntry.Custom element in row.Elements)
                    {
                        if (curCol > 0)
                        {
                            if (!languages.ContainsKey(element.LocalName))
                                languages.Add(element.LocalName, new System.Collections.Generic.Dictionary<string, string>());
                            languages[element.LocalName].Add(row.Title.Text, element.Value);
                        }
                        curCol++;
                    }

                    curCol = 0;
                }
            }

            foreach (var lang in languages)
            {
                var filepath = in_path + "/" + lang.Key + ".txt";
                var fs = System.IO.File.Open(filepath, System.IO.File.Exists(filepath) ?
                    System.IO.FileMode.Truncate :
                    System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);

                var sw = new System.IO.StreamWriter(fs);
                var fileString = System.String.Empty;

                fileString += FormatLine("Flag = Flag-" + lang.Key);
                fileString = lang.Value.Aggregate(fileString, (in_current, in_word) => in_current + FormatLine(in_word.Key + " = " + in_word.Value));
                sw.Write(fileString);
                sw.Close();
                fs.Close();
            }
        }
Esempio n. 21
0
 public virtual bool ContainsIndex(Net.Vpc.Upa.Index item, Net.Vpc.Upa.Entity parent)
 {
     return(indexes.ContainsKey(item.GetName()));
 }
Esempio n. 22
0
File: SCC2.cs Progetto: pszmyd/SHS
 public static void Main(string[] args)
 {
     if (args.Length != 2) {
       Console.Error.WriteLine("Usage: SHS.SCC2 <leader> <store>");
     } else {
       var sw = Stopwatch.StartNew();
       var shs = new Service(args[0]).OpenStore(Guid.Parse(args[1]));
       var map = shs.AllocateUidState<int>();  // Mapping from UID to local ID
       int numVerts = 0;  // Number of core vertices
       var batch = new Batch<long>(500000);
       foreach (long u in shs.Uids()) {
     batch.Add(u);
     if (batch.Full || shs.IsLastUid(u)) {
       int[] fwdDegs = shs.BatchedGetDegree(batch, Dir.Fwd);
       int[] bwdDegs = shs.BatchedGetDegree(batch, Dir.Bwd);
       var mapChunk = new int[batch.Count];
       for (int i = 0; i < batch.Count; i++) {
         mapChunk[i] = fwdDegs[i] == 0 || bwdDegs[i] == 0 ? -1 : numVerts++;
       }
       map.SetMany(batch, mapChunk);
       batch.Reset();
     }
       }
       uint numEdges = 0;
       foreach (var up in map.GetAll()) {
     if (up.val != -1) batch.Add(up.uid);
     if (batch.Full || shs.IsLastUid(up.uid)) {
       long[][] nbors = shs.BatchedGetLinks(batch, Dir.Fwd);
       int[] mappedNbors = map.GetMany(Flatten(nbors));
       int q = 0;
       for (int i = 0; i < nbors.Length; i++) {
         for (int j = 0; j < nbors[i].Length; j++) {
           if (mappedNbors[q++] != -1) numEdges++;
         }
       }
       batch.Reset();
     }
       }
       uint[] pastLast = new uint[numVerts]; // one past last link of that page
       var links = new int[numEdges];
       int p = 0;
       uint r = 0;
       foreach (var up in map.GetAll()) {
     if (up.val != -1) batch.Add(up.uid);
     if (batch.Full || shs.IsLastUid(up.uid)) {
       long[][] nbors = shs.BatchedGetLinks(batch, Dir.Fwd);
       int[] mappedNbors = map.GetMany(Flatten(nbors));
       int q = 0;
       for (int i = 0; i < nbors.Length; i++) {
         for (int j = 0; j < nbors[i].Length; j++) {
           int id = mappedNbors[q++];
           if (id != -1) links[r++] = id;
         }
         pastLast[p++] = r;
       }
       batch.Reset();
     }
       }
       var bv = new BitVector(numVerts);  // All false at creation
       int[] stk = new int[numVerts];
       int stkPtr = stk.Length;
       for (int u = 0; u < numVerts; u++) {
     if (!bv[u]) {
       bv[u] = true;
       Frame frame = new Frame(null, u, pastLast);
       while (frame != null) {
         while (frame.ctr < pastLast[frame.id]) {
           int v = links[frame.ctr++];
           if (!bv[v]) {
             bv[v] = true;
             frame = new Frame(frame, v, pastLast);
           }
         }
         stk[--stkPtr] = frame.id;
         frame = frame.parent;
       }
     }
       }
       p = 0;
       r = 0;
       foreach (var up in map.GetAll()) {
     if (up.val != -1) batch.Add(up.uid);
     if (batch.Full || shs.IsLastUid(up.uid)) {
       long[][] nbors = shs.BatchedGetLinks(batch, Dir.Bwd);
       int[] mappedNbors = map.GetMany(Flatten(nbors));
       int q = 0;
       for (int i = 0; i < nbors.Length; i++) {
         for (int j = 0; j < nbors[i].Length; j++) {
           int id = mappedNbors[q++];
           if (id != -1) links[r++] = id;
         }
         pastLast[p++] = r;
       }
       batch.Reset();
     }
       }
       var pam = new long[numVerts];
       p = 0;
       foreach (var up in map.GetAll()) {
     if (up.val != -1) pam[p++] = up.uid;
       }
       using (var sccWr = new BinaryWriter(new BufferedStream(new FileStream("scc-main.bin", FileMode.Create, FileAccess.Write)))) {
     using (var idxWr = new BinaryWriter(new BufferedStream(new FileStream("scc-index.bin", FileMode.Create, FileAccess.Write)))) {
       long sccPos = 0;
       bv.SetAll(false);
       for (int i = 0; i < stk.Length; i++) {
         int u = stk[i];
         if (!bv[u]) {
           long sccSize = 0;
           bv[u] = true;
           Frame frame = new Frame(null, u, pastLast);
           while (frame != null) {
             while (frame.ctr < pastLast[frame.id]) {
               int v = links[frame.ctr++];
               if (!bv[v]) {
                 bv[v] = true;
                 frame = new Frame(frame, v, pastLast);
               }
             }
             sccWr.Write(pam[frame.id]);
             sccSize++;
             frame = frame.parent;
           }
           idxWr.Write(sccSize);
           idxWr.Write(sccPos);
           sccPos += sccSize;
         }
       }
       foreach (var up in map.GetAll()) {
         if (up.val == -1) {
           sccWr.Write(up.uid);
           idxWr.Write(1L);
           idxWr.Write(sccPos++);
         }
       }
     }
       }
       var dict = new System.Collections.Generic.Dictionary<long, long>();
       using (var ib = new BinaryReader(new BufferedStream(new FileStream("scc-index.bin", FileMode.Open, FileAccess.Read)))) {
     while (true) {
       try {
         long size = ib.ReadInt64();
         long pos = ib.ReadInt64();
         if (!dict.ContainsKey(size)) dict[size] = 0;
         dict[size]++;
       } catch (EndOfStreamException) {
         break;
       }
     }
       }
       long maxSize = 0;
       long numSCCs = 0;
       foreach (var kv in dict) {
     if (kv.Key > maxSize) maxSize = kv.Key;
     numSCCs += kv.Value;
       }
       Console.WriteLine("Done. Job took {0} seconds.", 0.001 * sw.ElapsedMilliseconds);
     }
 }
        /// <summary>
        /// 得到调入单dto
        /// </summary>
        /// <param name="bpObj"></param>
        /// <returns></returns>
        private System.Collections.Generic.List <UFIDA.U9.ISV.TransferInISV.IC_TransferInDTOData> GetTransferInDTOList(System.Collections.Generic.List <CarShipLineDTO> transferinlist)
        {
            System.Collections.Generic.List <UFIDA.U9.ISV.TransferInISV.IC_TransferInDTOData> list = new System.Collections.Generic.List <UFIDA.U9.ISV.TransferInISV.IC_TransferInDTOData>();
            System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <CarShipLineDTO> > dic = new System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <CarShipLineDTO> >();
            foreach (CarShipLineDTO dtoline in transferinlist)
            {
                if (!dic.ContainsKey(dtoline.SpitOrderFlag))
                {
                    dic.Add(dtoline.SpitOrderFlag, new System.Collections.Generic.List <CarShipLineDTO>());
                }
                dic[dtoline.SpitOrderFlag].Add(dtoline);
            }
            foreach (string key in dic.Keys)
            {
                List <CarShipLineDTO> listLineDTO = dic[key];

                if (listLineDTO != null &&
                    listLineDTO.Count > 0
                    )
                {
                    CarShipLineDTO firstDTO = listLineDTO.GetFirst <CarShipLineDTO>();

                    UFIDA.U9.ISV.TransferInISV.IC_TransferInDTOData transindto = new UFIDA.U9.ISV.TransferInISV.IC_TransferInDTOData();
                    transindto.TransInDocType      = (new CommonArchiveDataDTOData());
                    transindto.TransInDocType.Code = ("CarOutWH");
                    transindto.CreatedBy           = (Context.LoginUser);
                    transindto.CreatedOn           = (System.DateTime.Now);
                    transindto.ModifiedBy          = (Context.LoginUser);
                    transindto.ModifiedOn          = (System.DateTime.Now);
                    transindto.TransInLines        = (new System.Collections.Generic.List <UFIDA.U9.ISV.TransferInISV.IC_TransInLineDTOData>());
                    foreach (CarShipLineDTO linedto in listLineDTO)
                    {
                        UFIDA.U9.ISV.TransferInISV.IC_TransInLineDTOData transinlinedto = new UFIDA.U9.ISV.TransferInISV.IC_TransInLineDTOData();
                        transinlinedto.ItemInfo          = (new ItemInfoData());
                        transinlinedto.ItemInfo.ItemCode = (linedto.ErpMaterialCode);
                        transinlinedto.TransInWh         = (new CommonArchiveDataDTOData());
                        transinlinedto.TransInWh.Code    = (linedto.WhIn);
                        Warehouse whin = Warehouse.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), linedto.WhIn), new OqlParam[0]);
                        if (whin != null)
                        {
                            transinlinedto.StorageType = (whin.StorageType.Value);
                        }
                        else
                        {
                            transinlinedto.StorageType = (4);
                        }
                        transinlinedto.StoreUOMQty                  = (linedto.Number);
                        transinlinedto.CostCurrency                 = (new CommonArchiveDataDTOData());
                        transinlinedto.CostCurrency.Code            = (linedto.Currency);
                        transinlinedto.Project                      = (new CommonArchiveDataDTOData());
                        transinlinedto.Project.Code                 = (linedto.DmsSaleNo);
                        transinlinedto.DescFlexSegments             = (new DescFlexSegmentsData());
                        transinlinedto.DescFlexSegments.PubDescSeg5 = (linedto.DmsSaleNo);
                        transinlinedto.TransInSubLines              = (new System.Collections.Generic.List <UFIDA.U9.ISV.TransferInISV.IC_TransInSubLineDTOData>());
                        UFIDA.U9.ISV.TransferInISV.IC_TransInSubLineDTOData sublinedto = new UFIDA.U9.ISV.TransferInISV.IC_TransInSubLineDTOData();
                        sublinedto.TransOutWh      = (new CommonArchiveDataDTOData());
                        sublinedto.TransOutWh.Code = (linedto.WhOut);
                        Warehouse whout = Warehouse.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), linedto.WhOut), new OqlParam[0]);
                        if (whout != null)
                        {
                            sublinedto.StorageType = (whout.StorageType.Value);
                        }
                        else
                        {
                            sublinedto.StorageType = (4);
                        }
                        sublinedto.Project      = (new CommonArchiveDataDTOData());
                        sublinedto.Project.Code = (linedto.DmsSaleNo);
                        transinlinedto.TransInSubLines.Add(sublinedto);
                        transindto.TransInLines.Add(transinlinedto);
                    }
                    list.Add(transindto);
                }
            }
            return(list);
        }
        /// <summary>
        /// 加入DataTable到DetailGrid中
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="dt"></param>
        /// <param name="primaryKeyName"></param>
        /// <param name="setValues"></param>
        public static void AddDetailDataTableRows(this IGrid grid, System.Data.DataTable dt, string primaryKeyName, SetOtherRowValues setValues)
        {
            System.Collections.Generic.Dictionary<string, Xceed.Grid.DataRow> masterRows =
                new System.Collections.Generic.Dictionary<string, Xceed.Grid.DataRow>();
            foreach (Xceed.Grid.DataRow row in grid.DataRows)
            {
                if (!masterRows.ContainsKey(row.Cells[primaryKeyName].Value.ToString()))
                {
                    masterRows[row.Cells[primaryKeyName].Value.ToString()] = row;
                }
            }

            for (int i = 0; i < dt.Rows.Count; ++i)
            {
                Xceed.Grid.DataRow row;
                if (!masterRows.ContainsKey(dt.Rows[i][primaryKeyName].ToString()))
                {
                    row = grid.AddDataRow(dt.Rows[i]);
                    masterRows[dt.Rows[i][primaryKeyName].ToString()] = row;
                }

                MyDetailGrid detailGrid =
                    masterRows[dt.Rows[i][primaryKeyName].ToString()].DetailGrids[0] as MyDetailGrid;
                row = detailGrid.AddDataRow(dt.Rows[i]);

                if (setValues != null)
                {
                    setValues(row);
                }
            }
        }
Esempio n. 25
0
 public static object GetObject(string key, object defval)
 {
     return(dic.ContainsKey(key) && dic[key] != null ? dic[key] : defval);
 }
Esempio n. 26
0
        /// <summary>The subSpans are ordered in the same doc, so there is a possible match.
        /// Compute the slop while making the match as short as possible by advancing
        /// all subSpans except the last one in reverse order.
        /// </summary>
        private bool ShrinkToAfterShortestMatch()
        {
            matchStart = subSpans[subSpans.Length - 1].Start();
            matchEnd = subSpans[subSpans.Length - 1].End();
            System.Collections.Generic.Dictionary<byte[], byte[]> possibleMatchPayloads = new System.Collections.Generic.Dictionary<byte[], byte[]>();
            if (subSpans[subSpans.Length - 1].IsPayloadAvailable())
            {
                System.Collections.Generic.ICollection<byte[]> payload = subSpans[subSpans.Length - 1].GetPayload();
                foreach(byte[] pl in payload)
                {
                    if (!possibleMatchPayloads.ContainsKey(pl))
                    {
                        possibleMatchPayloads.Add(pl, pl);
                    }
                }
            }

            System.Collections.Generic.List<byte[]> possiblePayload = null;

            int matchSlop = 0;
            int lastStart = matchStart;
            int lastEnd = matchEnd;
            for (int i = subSpans.Length - 2; i >= 0; i--)
            {
                Spans prevSpans = subSpans[i];
                if (collectPayloads && prevSpans.IsPayloadAvailable())
                {
                    System.Collections.Generic.ICollection<byte[]> payload = prevSpans.GetPayload();
                    possiblePayload = new System.Collections.Generic.List<byte[]>(payload.Count);
                    possiblePayload.AddRange(payload);
                }

                int prevStart = prevSpans.Start();
                int prevEnd = prevSpans.End();
                while (true)
                {
                    // Advance prevSpans until after (lastStart, lastEnd)
                    if (!prevSpans.Next())
                    {
                        inSameDoc = false;
                        more = false;
                        break; // Check remaining subSpans for final match.
                    }
                    else if (matchDoc != prevSpans.Doc())
                    {
                        inSameDoc = false; // The last subSpans is not advanced here.
                        break; // Check remaining subSpans for last match in this document.
                    }
                    else
                    {
                        int ppStart = prevSpans.Start();
                        int ppEnd = prevSpans.End(); // Cannot avoid invoking .end()
                        if (!DocSpansOrdered(ppStart, ppEnd, lastStart, lastEnd))
                        {
                            break; // Check remaining subSpans.
                        }
                        else
                        {
                            // prevSpans still before (lastStart, lastEnd)
                            prevStart = ppStart;
                            prevEnd = ppEnd;
                            if (collectPayloads && prevSpans.IsPayloadAvailable())
                            {
                                System.Collections.Generic.ICollection<byte[]> payload = prevSpans.GetPayload();
                                possiblePayload = new System.Collections.Generic.List<byte[]>(payload.Count);
                                possiblePayload.AddRange(payload);
                            }
                        }
                    }
                }

                if (collectPayloads && possiblePayload != null)
                {
                    foreach (byte[] pl in possiblePayload)
                    {
                        if (!possibleMatchPayloads.ContainsKey(pl))
                        {
                            possibleMatchPayloads.Add(pl, pl);
                        }
                    }
                }

                System.Diagnostics.Debug.Assert(prevStart <= matchStart);
                if (matchStart > prevEnd)
                {
                    // Only non overlapping spans add to slop.
                    matchSlop += (matchStart - prevEnd);
                }

                /* Do not break on (matchSlop > allowedSlop) here to make sure
                * that subSpans[0] is advanced after the match, if any.
                */
                matchStart = prevStart;
                lastStart = prevStart;
                lastEnd = prevEnd;
            }

            bool match = matchSlop <= allowedSlop;

            if (collectPayloads && match && possibleMatchPayloads.Count > 0)
            {
                matchPayload.AddRange(possibleMatchPayloads.Keys);
            }

            return match; // ordered and allowed slop
        }
Esempio n. 27
0
        private static void MergeXml(XmlDocument d1, XmlNode n1, string xpath1, XmlDocument d2, XmlNode n2, string xpath2)
        {
            System.Collections.Generic.Dictionary<string, XmlNode> ch1nodes = new System.Collections.Generic.Dictionary<string,XmlNode>();
            foreach (XmlNode ch1 in n1.ChildNodes)
            {
                ch1nodes[GetXmlNodeKey(ch1)] = ch1;
            }

            foreach (XmlNode ch2 in n2.ChildNodes)
            {
                string ch2Key = GetXmlNodeKey(ch2);

                XmlNode ch1 = null;
                if (ch1nodes.ContainsKey(ch2Key))
                {
                    ch1 = ch1nodes[ch2Key];

                    if (ch2.Attributes["n"] != null && ch1.Attributes["n"] == null)
                        ch1.Attributes.Append(ch2.Attributes["n"].Clone() as XmlAttribute);

                    else if (ch2.Attributes["v"] != null && ch1.Attributes["v"] == null)
                        ch1.Attributes.Append(ch2.Attributes["v"].Clone() as XmlAttribute);

                    if (ch2.HasChildNodes)
                    {
                        MergeXml(d1, ch1, xpath1 + ch2Key, d2, ch2, xpath2 + ch2Key);
                    }
                }
                else 
                {
                    //ch1 = ch2.CloneNode(true);
                    ch1 = d1.ImportNode(ch2, true);
                    n1.AppendChild(ch1);
                }
            }
        }
        private IEnumerator GetAndSendMedPollData()
        {
            //Orbit data
            System.Collections.Generic.Dictionary<string, double> DoubleValues = new System.Collections.Generic.Dictionary<string, double>();
            System.Collections.Generic.Dictionary<string, string> StringValues = new System.Collections.Generic.Dictionary<string, string>();

            StringValues ["o.body"] = this.vessel.orbit.referenceBody.GetName ();
            DoubleValues ["o.ApA"] = this.vessel.orbit.ApA;
            DoubleValues ["o.PeA"] = this.vessel.orbit.PeA;
            DoubleValues ["o.timeToAp"] = this.vessel.orbit.timeToAp;
            DoubleValues ["o.timeToPe"] = this.vessel.orbit.timeToPe;
            DoubleValues ["o.inclination"] = this.vessel.orbit.inclination;
            DoubleValues ["o.eccentricity"] = this.vessel.orbit.eccentricity;
            StringValues ["o.type"] = "Regular Orbit";
            if (this.vessel.orbit.patchEndTransition == Orbit.PatchTransitionType.ENCOUNTER) {
                StringValues ["o.type"] = "Encounter";
            }
            if (this.vessel.orbit.patchEndTransition == Orbit.PatchTransitionType.ESCAPE) {
                StringValues ["o.type"] = "Escape";
            }

            StringValues ["o.n.body"] = "No Orbit";
            DoubleValues ["o.n.ApA"] = double.NaN;
            DoubleValues ["o.n.PeA"] = double.NaN;
            DoubleValues ["o.n.timeToAp"] = double.NaN;
            DoubleValues ["o.n.timeToPe"] = double.NaN;
            DoubleValues ["o.n.inclination"] = double.NaN;
            DoubleValues ["o.n.eccentricity"] = double.NaN;
            StringValues ["o.n.type"] = "Regular Orbit";
            DoubleValues ["o.n.escape"] = double.NaN;

            if (this.vessel.orbit.nextPatch != null && this.vessel.orbit.nextPatch.activePatch == true) {
                StringValues ["o.n.body"] = this.vessel.orbit.nextPatch.referenceBody.GetName ();
                DoubleValues ["o.n.ApA"] = this.vessel.orbit.nextPatch.ApA;
                DoubleValues ["o.n.PeA"] = this.vessel.orbit.nextPatch.PeA;
                DoubleValues ["o.n.timeToAp"] = this.vessel.orbit.nextPatch.timeToAp;
                DoubleValues ["o.n.timeToPe"] = this.vessel.orbit.nextPatch.timeToPe;
                DoubleValues ["o.n.inclination"] = this.vessel.orbit.nextPatch.inclination;
                DoubleValues ["o.n.eccentricity"] = this.vessel.orbit.nextPatch.eccentricity;
                if (this.vessel.orbit.nextPatch.patchEndTransition == Orbit.PatchTransitionType.ENCOUNTER) {
                    StringValues ["o.n.type"] = "Encounter";
                }
                if (this.vessel.orbit.nextPatch.patchEndTransition == Orbit.PatchTransitionType.ESCAPE) {
                    StringValues ["o.n.type"] = "Escape";
                }
            }

            //Resource data
            System.Collections.Generic.Dictionary<string, double> ResourceCurrent = new System.Collections.Generic.Dictionary<string, double>();
            System.Collections.Generic.Dictionary<string, double> ResourceMax = new System.Collections.Generic.Dictionary<string, double>();

            DoubleValues ["v.overheatRatio"] = 0.0d;

            foreach (Part part in this.vessel.parts) {
                //resources
                if (part.Resources.Count > 0) {
                    foreach (PartResource partResource in part.Resources) {
                        if (!ResourceCurrent.ContainsKey(partResource.resourceName)) { ResourceCurrent [partResource.resourceName] = 0; }
                        if (!ResourceMax.ContainsKey(partResource.resourceName))     { ResourceMax     [partResource.resourceName] = 0; }
                        ResourceCurrent [partResource.resourceName] += partResource.amount;
                        ResourceMax     [partResource.resourceName] += partResource.maxAmount;
                    }
                }
                //overheat
                foreach (PartModule pm in part.Modules) {
                    if (!pm.isEnabled) { continue; }
                    var thatEngineModule = pm as ModuleEngines;
                    var thatEngineModuleFX = pm as ModuleEnginesFX;
                    if (thatEngineModule != null || thatEngineModuleFX != null) {
                        double thistempratio = part.temperature / part.maxTemp;
                        DoubleValues ["v.overheatRatio"] = (thistempratio > DoubleValues ["v.overheatRatio"]) ? thistempratio : DoubleValues ["v.overheatRatio"];
                    }
                }
            }
            DoubleValues ["v.overheat"] = 0.0;
            foreach (Part thatPart in this.vessel.parts) {

            }
            //POST DATA
            var form = new WWWForm();
            form.AddField("type", "med");
            form.AddField("time", helpers.UnixTimeAsString());
            foreach (System.Collections.Generic.KeyValuePair<string, double> entry in DoubleValues)
            {
                form.AddField(entry.Key,entry.Value.ToString());
            }
            foreach (System.Collections.Generic.KeyValuePair<string, string> entry in StringValues)
            {
                form.AddField(entry.Key,entry.Value);
            }
            foreach (System.Collections.Generic.KeyValuePair<string, double> entry in ResourceCurrent)
            {
                form.AddField("r.resource["+entry.Key+"]", ResourceCurrent[entry.Key].ToString());
            }
            foreach (System.Collections.Generic.KeyValuePair<string, double> entry in ResourceMax)
            {
                form.AddField("r.resourceMax["+entry.Key+"]", ResourceMax[entry.Key].ToString());
            }
            var post = new WWW(postlocation,form);
            yield return post;
            if (!string.IsNullOrEmpty(post.error))
                print("GetAndSendMedPollData: WWWFORM ERROR:" + post.error);
            next_med_poll_time = Time.time + med_freq;
        }
Esempio n. 29
0
 /// <summary>
 /// Gets the CAML query for well book pages.
 /// </summary>
 /// <returns>CAML query for well book pages.</returns>
 private string GetCAMLQueryForWellBookPages()
 {
     string strCamlQuery = string.Empty;
     StringBuilder sbChapterId = new StringBuilder();
     DataTable dtListDetails = null;
     string strTerminated = string.Empty;
     if (!ActiveStatus)
         strTerminated = STATUS_TERMINATED;
     else
         strTerminated = STATUS_ACTIVE;
     string strBookId = HttpContext.Current.Request.QueryString["BookId"];
     if (string.IsNullOrEmpty(strBookId))
         return string.Empty;
     objCommonBLL = new CommonBLL();
     strCamlQuery = @"<Where><Eq><FieldRef Name='Book_ID' /><Value Type='Number'>" +
      strBookId + "</Value></Eq></Where>";
     dtListDetails = objCommonBLL.ReadList(strSiteURL, CHAPTERLIST, strCamlQuery);
     if (dtListDetails != null && dtListDetails.Rows.Count > 0)
     {
         dicChatperDetail = new System.Collections.Generic.Dictionary<string, string>();
         for (int intRowIndex = 0; intRowIndex < dtListDetails.Rows.Count; intRowIndex++)
         {
             if (!dicChatperDetail.ContainsKey(Convert.ToString(dtListDetails.Rows[intRowIndex]["ID"])))
             {
                 dicChatperDetail.Add(Convert.ToString(dtListDetails.Rows[intRowIndex]["ID"]), Convert.ToString(dtListDetails.Rows[intRowIndex]["Title"]));
                 sbChapterId.Append(Convert.ToString(dtListDetails.Rows[intRowIndex]["ID"]));
                 sbChapterId.Append(";");
             }
         }
         strCamlQuery = CreateCAMLQueryForSetOfCondtion(sbChapterId.ToString(), "Chapter_ID", "Number");
         sbChapterId.Remove(0, sbChapterId.Length);
         sbChapterId.Append(strCamlQuery);
         sbChapterId.Append("<Eq><FieldRef Name='Terminate_Status' /><Value Type='Choice'>" + strTerminated + "</Value></Eq></And></Where>");
         sbChapterId.Insert(0, "<Where><And>");
         sbChapterId.Insert(0, "<OrderBy><FieldRef Name='Page_Name' /></OrderBy>");
     }
     if (dtListDetails != null)
     {
         dtListDetails.Dispose();
     }
     return sbChapterId.ToString();
 }
Esempio n. 30
0
        List<mTuple<bool, SubCalendarEvent>> stitchUnRestrictedSubCalendarEvent(TimeLine FreeBoundary, List<mTuple<bool, SubCalendarEvent>> restrictedSnugFitAvailable, Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>> PossibleEntries, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> CompatibleWithList,double Occupancy)
        {
            TimeLine[] AllFreeSpots = FreeBoundary.getAllFreeSlots();
            int TotalEventsForThisTImeLine = 0;

            foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair in CompatibleWithList)
            {
                TotalEventsForThisTImeLine += eachKeyValuePair.Value.Item1;
            }

            CompatibleWithList.Clear();


            DateTime EarliestReferenceTIme = FreeBoundary.Start;
            List<mTuple<bool, SubCalendarEvent>> FrontPartials = new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>();
            List<mTuple<bool, SubCalendarEvent>> EndPartials = new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>();
            Dictionary<DateTime, List<mTuple<bool, SubCalendarEvent>>> FrontPartials_Dict = new System.Collections.Generic.Dictionary<DateTime, System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>>();
            Dictionary<DateTime, List<mTuple<bool, SubCalendarEvent>>> EndPartials_Dict = new System.Collections.Generic.Dictionary<DateTime, System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>>();
            Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>> PossibleEntries_Cpy = new Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>>();
            Dictionary<string, Dictionary<string, SubCalendarEvent>> CalendarIDAndNonPartialSubCalEvents = new Dictionary<string, Dictionary<string, SubCalendarEvent>>();//List of non partials for current Reference StartTime To End of FreeBoundary. Its gets updated with Partials once the earliest reference time passes the partial event start time

            foreach (KeyValuePair<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>> eachKeyValuePair in PossibleEntries)//populates PossibleEntries_Cpy. I need a copy to maintain all references to PossibleEntries
            {
                Dictionary<string, mTuple<bool, SubCalendarEvent>> NewDictEntry = new Dictionary<string, mTuple<bool, SubCalendarEvent>>();
                
                foreach (KeyValuePair<string, mTuple<bool, SubCalendarEvent>> KeyValuePair0 in eachKeyValuePair.Value)
                {
                    mTuple<bool, SubCalendarEvent> MyEvent = KeyValuePair0.Value;

                    if (MyEvent.Item2.ID == "469_471")
                    {
                        ;
                    }

                    bool isInrestrictedSnugFitAvailable = false;
                    if (CompatibleWithList.ContainsKey(eachKeyValuePair.Key))
                    {
                        ++CompatibleWithList[eachKeyValuePair.Key].Item1;
                    }
                    else
                    {
                        CompatibleWithList.Add(eachKeyValuePair.Key, new mTuple<int, TimeSpanWithStringID>(1, new TimeSpanWithStringID(KeyValuePair0.Value.Item2.ActiveDuration, KeyValuePair0.Value.Item2.ActiveDuration.Ticks.ToString())));
                    }

                    foreach (mTuple<bool, SubCalendarEvent> eachMtuple in restrictedSnugFitAvailable)//checks if event is in restricted list
                    {
                        if (eachMtuple.Item2.ID == MyEvent.Item2.ID)
                        {
                            isInrestrictedSnugFitAvailable = true;
                            break;
                        }

                    }


                    if (!isInrestrictedSnugFitAvailable)
                    {
                        NewDictEntry.Add(KeyValuePair0.Value.Item2.ID, KeyValuePair0.Value);
                        if (FreeBoundary.IsDateTimeWithin(KeyValuePair0.Value.Item2.getCalendarEventRange.Start))
                        {
                            FrontPartials.Add(KeyValuePair0.Value);
                        }
                        else
                        {
                            if (FreeBoundary.IsDateTimeWithin(KeyValuePair0.Value.Item2.getCalendarEventRange.End))
                            {
                                EndPartials.Add(KeyValuePair0.Value);
                            }
                            else 
                            {
                                string CalLevel0ID=KeyValuePair0.Value.Item2.SubEvent_ID.getLevelID(0);
                                if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(CalLevel0ID))
                                {
                                    CalendarIDAndNonPartialSubCalEvents[CalLevel0ID].Add(KeyValuePair0.Value.Item2.ID, KeyValuePair0.Value.Item2);
                                }
                                else 
                                {
                                    //CalendarIDAndNonPartialSubCalEvents.Add(CalLevel0ID, new List<SubCalendarEvent>() { KeyValuePair0.Value.Item2 });
                                    CalendarIDAndNonPartialSubCalEvents.Add(CalLevel0ID, new Dictionary<string, SubCalendarEvent>());
                                    CalendarIDAndNonPartialSubCalEvents[CalLevel0ID].Add(KeyValuePair0.Value.Item2.ID, KeyValuePair0.Value.Item2);
                                }
                            
                            }
                        }
                    }
                }
                if (NewDictEntry.Count > 0)
                { PossibleEntries_Cpy.Add(eachKeyValuePair.Key, NewDictEntry); }

            }

            FrontPartials = FrontPartials.OrderBy(obj => obj.Item2.getCalendarEventRange.Start).ToList();
            EndPartials = EndPartials.OrderBy(obj => obj.Item2.getCalendarEventRange.End).ToList();

            foreach (mTuple<bool, SubCalendarEvent> eachmTuple in FrontPartials)//populates FrontPartials_Dict in ordered manner since FrontPartials is ordered
            {
                if (FrontPartials_Dict.ContainsKey(eachmTuple.Item2.getCalendarEventRange.Start))
                {
                    FrontPartials_Dict[eachmTuple.Item2.getCalendarEventRange.Start].Add(eachmTuple);
                }
                else
                {
                    FrontPartials_Dict.Add(eachmTuple.Item2.getCalendarEventRange.Start, new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>() { eachmTuple });
                }

            }

            foreach (mTuple<bool, SubCalendarEvent> eachmTuple in EndPartials)//populates EndPartials_Dict in ordered manner since EndPartials is ordered
            {
                if (EndPartials_Dict.ContainsKey(eachmTuple.Item2.getCalendarEventRange.Start))
                {
                    EndPartials_Dict[eachmTuple.Item2.getCalendarEventRange.Start].Add(eachmTuple);
                }
                else
                {
                    EndPartials_Dict.Add(eachmTuple.Item2.getCalendarEventRange.Start, new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>() { eachmTuple });
                }
            }


            List<SubCalendarEvent> CompleteArranegement = new System.Collections.Generic.List<SubCalendarEvent>();
            int StartingReferneceIndex = 0;


            /*foreach (mTuple<bool, SubCalendarEvent> eachmTuple in restrictedSnugFitAvailable)//removes the restricted from CompatibleWithList
            {
                --CompatibleWithList[eachmTuple.Item2.ActiveDuration.Ticks.ToString()].Item1;
                //PossibleEntries_Cpy[eachmTuple.Item2.ActiveDuration.Ticks.ToString()].Remove(eachmTuple.Item2.ID);
            }*/

            List<DateTime> ListOfFrontPartialsStartTime = FrontPartials_Dict.Keys.ToList();

            int i = 0;
            int j = 0;
            int FrontPartialCounter = 0;

            if (restrictedSnugFitAvailable.Count < 1)
            {
                ;
            }

            Tuple<DateTime, List<SubCalendarEvent>> TimeLineUpdated = null;
            SubCalendarEvent BorderElementBeginning = null;
            SubCalendarEvent BorderElementEnd = null;
            SubCalendarEvent LastSubCalElementForEarlierReferenceTime = null;
            for (; i < restrictedSnugFitAvailable.Count; i++)
            {
                //bool isFreeSpotBeforeRigid = AllFreeSpots[i].End <= restrictedSnugFitAvailable[i].Item2.Start;
                TimeLineUpdated = null;

                if (CompleteArranegement.Count == 46)
                {
                    ;
                }

                if (i ==2)
                {
                    ;
                }

                restrictedSnugFitAvailable[i].Item2.PinSubEventsToStart(new TimeLine(EarliestReferenceTIme, restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End));
                List<BusyTimeLine> RestrictedBusySlots = new System.Collections.Generic.List<BusyTimeLine>();
                FreeBoundary = new TimeLine(FreeBoundary.Start, FreeBoundary.End);
                foreach (mTuple<bool, SubCalendarEvent> eachmTuple in restrictedSnugFitAvailable)
                {
                    eachmTuple.Item1 = true;
                    RestrictedBusySlots.Add(eachmTuple.Item2.ActiveSlot);
                    string timeSpanString = eachmTuple.Item2.ActiveDuration.Ticks.ToString();
                    string SubEventID = eachmTuple.Item2.ID;

                }
                FreeBoundary.AddBusySlots(RestrictedBusySlots.ToArray());

                List<SubCalendarEvent> LowestCostArrangement = new System.Collections.Generic.List<SubCalendarEvent>();
                TimeLine PertinentFreeSpot = null;
                TimeLine FreeSpotUpdated = null;
                j = i + 1;
                if (ListOfFrontPartialsStartTime.Count > 0)//fits any sub calEvent in preceeding restricting free spot
                {
                    DateTime RestrictedStopper = restrictedSnugFitAvailable[i].Item2.Start;


                    bool breakForLoop = false;
                    bool PreserveRestrictedIndex = false;
                    for (; FrontPartialCounter < ListOfFrontPartialsStartTime.Count; FrontPartialCounter++)
                    {
                        TimeLineUpdated = null;
                        DateTime PertinentFreeSpotStart = EarliestReferenceTIme;
                        DateTime PertinentFreeSpotEnd;
                        if (CompleteArranegement.Count == 46)
                        {
                            ;
                        }
                        if ((ListOfFrontPartialsStartTime[FrontPartialCounter] < RestrictedStopper))
                        {
                            PertinentFreeSpotEnd = ListOfFrontPartialsStartTime[FrontPartialCounter];
                            //FrontPartials_Dict.Remove(ListOfFrontPartialsStartTime[FrontPartialCounter]);
                            ListOfFrontPartialsStartTime.RemoveAt(FrontPartialCounter);
                            --FrontPartialCounter;
                            PreserveRestrictedIndex = true;
                        }
                        else
                        {
                            PertinentFreeSpotEnd = RestrictedStopper;

                            if (breakForLoop)
                            {//populates with final boundary for each restricted
                                PertinentFreeSpot = new TimeLine(PertinentFreeSpotStart, PertinentFreeSpotEnd);

                                BorderElementBeginning = CompleteArranegement.Count>0?CompleteArranegement[CompleteArranegement.Count-1]:null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                                BorderElementEnd = restrictedSnugFitAvailable[i].Item2;//uses restricted value as boundary element
                                LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy,Occupancy);
                                DateTime EarliestTimeForBetterEarlierReferenceTime = PertinentFreeSpot.Start;
                                LastSubCalElementForEarlierReferenceTime = ((CompleteArranegement.Count < 1) || (CompleteArranegement == null) ? null : CompleteArranegement[CompleteArranegement.Count - 1]);
                                    FreeSpotUpdated = PertinentFreeSpot.CreateCopy();
                                if (LowestCostArrangement.Count > 0)
                                {
                                    if (!(LowestCostArrangement[0].getCalendarEventRange.Start == PertinentFreeSpot.Start))//Pin SubEvents To Start
                                    {//if the first element is not a partial Sub Cal Event element
                                        FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                                    }
                                    else
                                    {
                                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();// new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                                        Utility.PinSubEventsToStart(LowestCostArrangement, PertinentFreeSpot);
                                    }
                                    EarliestReferenceTIme = PertinentFreeSpot.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;

                                    SubCalendarEvent LastSubCalEvent = LowestCostArrangement[LowestCostArrangement.Count - 1];
                                    EarliestTimeForBetterEarlierReferenceTime = LastSubCalEvent.End;
                                    LastSubCalElementForEarlierReferenceTime = LastSubCalEvent;
                                    
                                }
                                TimeLineUpdated = null;
                                TimeLineUpdated = ObtainBetterEarlierReferenceTime(LowestCostArrangement, CalendarIDAndNonPartialSubCalEvents, RestrictedStopper - EarliestTimeForBetterEarlierReferenceTime, EarliestReferenceTIme, new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End), LastSubCalElementForEarlierReferenceTime);
                                if (TimeLineUpdated != null)
                                {
                                    LowestCostArrangement = TimeLineUpdated.Item2;
                                    EarliestReferenceTIme = TimeLineUpdated.Item1;
                                }
                                

                                foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                                {
                                    --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                                    PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                                    string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                                    if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                                    {
                                        CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                                        if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                                        {
                                            CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                                        }
                                    }
                                    if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                                    {
                                        PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                                    }
                                }


                                LowestCostArrangement = CompleteArranegement.Concat(LowestCostArrangement).ToList();
                                LowestCostArrangement = PlaceSubCalEventInLowestCostPosition(FreeBoundary, restrictedSnugFitAvailable[i].Item2, LowestCostArrangement);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeBoundary);

                                CompleteArranegement = LowestCostArrangement;
                                EarliestReferenceTIme = LowestCostArrangement[LowestCostArrangement.Count - 1].End;

                                PreserveRestrictedIndex = false;
                                break;
                            }

                            --FrontPartialCounter;
                            if (j < restrictedSnugFitAvailable.Count)
                            {
                                RestrictedStopper = restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End > restrictedSnugFitAvailable[j].Item2.Start ? restrictedSnugFitAvailable[j].Item2.Start : restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End;
                            }
                            else
                            {
                                RestrictedStopper = restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End > FreeBoundary.End ? FreeBoundary.End : restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End;
                            }
                            RestrictedStopper -= restrictedSnugFitAvailable[i].Item2.ActiveDuration;
                            breakForLoop = true;
                        }
                        PertinentFreeSpot = new TimeLine(PertinentFreeSpotStart, PertinentFreeSpotEnd);

                        BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                        BorderElementEnd = restrictedSnugFitAvailable[i].Item2;//uses restricted value as boundary element

                        LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy, Occupancy);
                        DateTime LatestDaterforEarlierReferenceTime = PertinentFreeSpot.Start;
                        LastSubCalElementForEarlierReferenceTime = ((CompleteArranegement.Count < 1) || (CompleteArranegement == null) ? null : CompleteArranegement[CompleteArranegement.Count - 1]);//updates the last element as either null or the last element in the current Complete arrangement
                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();
                        if (LowestCostArrangement.Count > 0)
                        {
                            if (!(LowestCostArrangement[0].getCalendarEventRange.Start == PertinentFreeSpot.Start))//Pin SubEvents To Start
                            {//if the first element is not a partial Sub Cal Event element
                                FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);

                            }
                            else
                            {
                                //FreeSpotUpdated = new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                                FreeSpotUpdated = PertinentFreeSpot.CreateCopy();
                                Utility.PinSubEventsToStart(LowestCostArrangement, PertinentFreeSpot);
                            }
                            EarliestReferenceTIme = PertinentFreeSpot.End;
                            
                            ///Comeback to this
                            ///
                            SubCalendarEvent LastSubCalEvent = LowestCostArrangement[LowestCostArrangement.Count - 1];
                            LatestDaterforEarlierReferenceTime = LastSubCalEvent.End;
                            LastSubCalElementForEarlierReferenceTime = LastSubCalEvent;
                        }

                        TimeLineUpdated = ObtainBetterEarlierReferenceTime(LowestCostArrangement, CalendarIDAndNonPartialSubCalEvents, RestrictedStopper - LatestDaterforEarlierReferenceTime, EarliestReferenceTIme, new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End), LastSubCalElementForEarlierReferenceTime);
                        //errorline
                        
                        if (TimeLineUpdated != null)
                        {
                            LowestCostArrangement = TimeLineUpdated.Item2;
                            EarliestReferenceTIme = TimeLineUpdated.Item1;
                        }
                        

                        foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                        {
                            --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                            PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                            string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                            if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                            {
                                CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                                if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                                {
                                    CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                                }
                            }
                            if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                            {
                                PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                            }
                        }
                        CompleteArranegement.AddRange(LowestCostArrangement);


                        int DateTimeCounter = 0;
                        for (; DateTimeCounter < FrontPartials_Dict.Keys.Count; DateTimeCounter++)//updates CalendarIDAndNonPartialSubCalEvents if frontpartial Startime has been passed. Alls updates FrontPartials_Dict
                        {
                            DateTime eachDateTIme = FrontPartials_Dict.Keys.ToList()[DateTimeCounter];
                            if (EarliestReferenceTIme >= eachDateTIme)
                            {
                                List<mTuple<bool, SubCalendarEvent>> mTUpleSubCalEvents = FrontPartials_Dict[eachDateTIme];
                                foreach (mTuple<bool, SubCalendarEvent> eachmTUple in mTUpleSubCalEvents)
                                {

                                    string CalLevel0ID = eachmTUple.Item2.SubEvent_ID.getLevelID(0);
                                    if (!CompleteArranegement.Contains(eachmTUple.Item2))
                                    {
                                        if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(CalLevel0ID))
                                        {
                                            CalendarIDAndNonPartialSubCalEvents[CalLevel0ID].Add(eachmTUple.Item2.ID, eachmTUple.Item2);
                                        }
                                        else
                                        {
                                            //CalendarIDAndNonPartialSubCalEvents.Add(CalLevel0ID, new List<SubCalendarEvent>() { KeyValuePair0.Value.Item2 });
                                            CalendarIDAndNonPartialSubCalEvents.Add(CalLevel0ID, new Dictionary<string, SubCalendarEvent>());
                                            CalendarIDAndNonPartialSubCalEvents[CalLevel0ID].Add(eachmTUple.Item2.ID, eachmTUple.Item2);
                                        }
                                    }
                                }
                                FrontPartials_Dict.Remove(eachDateTIme);
                            }
                        }


                    }
                    if (PreserveRestrictedIndex)//verifies if we took the path of restricted or front partial element. The latter needs a preservation of the current restricted Subcalevent index index 
                    {
                        --i;
                    }
                }
                else
                {//No FrontPartials
                    DateTime ReferenceEndTime = restrictedSnugFitAvailable[i].Item2.Start;
                    PertinentFreeSpot = new TimeLine(EarliestReferenceTIme, ReferenceEndTime);

                    BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                    BorderElementEnd = restrictedSnugFitAvailable[i].Item2;//uses restricted value as boundary element

                    LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy,Occupancy);

                    if (LowestCostArrangement.Count > 0)
                    {
                        if (!(LowestCostArrangement[0].getCalendarEventRange.Start == PertinentFreeSpot.Start))//Pin SubEvents To Start
                        {//if the first element is not a partial Sub Cal Event element
                            FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                            Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                        }
                        else
                        {
                            FreeSpotUpdated = new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                            Utility.PinSubEventsToStart(LowestCostArrangement, PertinentFreeSpot);
                        }
                        EarliestReferenceTIme = FreeSpotUpdated.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;
                    }

                    foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                    {
                        --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                        PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                        string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                        if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                        {
                            CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                            if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                            {
                                CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                            }
                        }
                        if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                        {
                            PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                        }
                    }


                    List<SubCalendarEvent> AdditionalCOstArrangement = new System.Collections.Generic.List<SubCalendarEvent>();
                    if (j < restrictedSnugFitAvailable.Count)
                    {
                        DateTime StartDateTimeAfterFitting = PertinentFreeSpot.End;//this is the barring end time of the preceding boundary search

                        DateTime RelativeEndTime = restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End > restrictedSnugFitAvailable[j].Item2.Start ? restrictedSnugFitAvailable[j].Item2.Start : restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End;

                        RelativeEndTime -= restrictedSnugFitAvailable[i].Item2.ActiveDuration;
                        TimeLine CurrentlyFittedTimeLine = new TimeLine(StartDateTimeAfterFitting, RelativeEndTime);

                        BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                        BorderElementEnd = restrictedSnugFitAvailable[i].Item2;//uses restricted value as boundary element

                        AdditionalCOstArrangement = OptimizeArrangeOfSubCalEvent(CurrentlyFittedTimeLine, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy, Occupancy);
                        if (AdditionalCOstArrangement.Count > 0)
                        {//Additional get populated
                            if (!(AdditionalCOstArrangement[0].getCalendarEventRange.Start == CurrentlyFittedTimeLine.Start))//Pin SubEvents To Start
                            {//if the first element is not a partial Sub Cal Event element
                                FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, CurrentlyFittedTimeLine.End);
                                Utility.PinSubEventsToStart(AdditionalCOstArrangement, FreeSpotUpdated);
                            }
                            else
                            {
                                FreeSpotUpdated = new TimeLine(AdditionalCOstArrangement[0].getCalendarEventRange.Start, CurrentlyFittedTimeLine.End);
                                Utility.PinSubEventsToStart(AdditionalCOstArrangement, FreeSpotUpdated);
                            }

                            foreach (SubCalendarEvent eachSubCalendarEvent in AdditionalCOstArrangement)
                            {
                                --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                                PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                                string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                                if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                                {
                                    CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                                    if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                                    {
                                        CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                                    }
                                }
                                if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                                {
                                    PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                                }
                            }


                            RelativeEndTime = AdditionalCOstArrangement[AdditionalCOstArrangement.Count - 1].End;
                            RelativeEndTime += restrictedSnugFitAvailable[i].Item2.ActiveDuration; ;
                            FreeSpotUpdated = new TimeLine(FreeSpotUpdated.Start, RelativeEndTime);
                            AdditionalCOstArrangement = PlaceSubCalEventInLowestCostPosition(FreeSpotUpdated, restrictedSnugFitAvailable[i].Item2, AdditionalCOstArrangement);
                        }
                        else
                        {//if there is no other Restricted in list
                            RelativeEndTime += restrictedSnugFitAvailable[i].Item2.ActiveDuration;

                            CurrentlyFittedTimeLine = new TimeLine(CurrentlyFittedTimeLine.Start, RelativeEndTime);

                            AdditionalCOstArrangement = PlaceSubCalEventInLowestCostPosition(CurrentlyFittedTimeLine, restrictedSnugFitAvailable[i].Item2, AdditionalCOstArrangement);
                        }
                    }
                    else
                    {
                        DateTime RelativeEndTime = restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End > FreeBoundary.End ? FreeBoundary.End : restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End;
                        TimeLine CurrentlyFittedTimeLine = new TimeLine(EarliestReferenceTIme, RelativeEndTime);
                        AdditionalCOstArrangement = PlaceSubCalEventInLowestCostPosition(CurrentlyFittedTimeLine, restrictedSnugFitAvailable[i].Item2, AdditionalCOstArrangement);
                    }

                    List<SubCalendarEvent> var2 = new System.Collections.Generic.List<SubCalendarEvent>();//List is a addition of LowestCostArrangement and AdditionalCOstArrangement
                    var2 = LowestCostArrangement.Concat(AdditionalCOstArrangement).ToList();

                    CompleteArranegement.AddRange(LowestCostArrangement);
                    CompleteArranegement.AddRange(AdditionalCOstArrangement);
                    if (CompleteArranegement.Count > 0)
                    {
                        EarliestReferenceTIme = CompleteArranegement[CompleteArranegement.Count - 1].End;
                    }
                }
            }


            { //Handles THe Last Free Space outside of rigids
                TimeLine FreeSpotOutSideRigids = new TimeLine(EarliestReferenceTIme, FreeBoundary.End);
                TimeLine PertinentFreeSpot = new TimeLine(EarliestReferenceTIme, FreeBoundary.End); ;
                TimeLine FreeSpotUpdated;
                List<SubCalendarEvent> LowestCostArrangement;
                if (ListOfFrontPartialsStartTime.Count > 0)
                {
                    for (FrontPartialCounter = 0; FrontPartialCounter < ListOfFrontPartialsStartTime.Count; FrontPartialCounter++)
                    {
                        DateTime PertinentFreeSpotStart = EarliestReferenceTIme;
                        DateTime PertinentFreeSpotEnd;
                        PertinentFreeSpotEnd = ListOfFrontPartialsStartTime[FrontPartialCounter];
                        //FrontPartials_Dict.Remove(ListOfFrontPartialsStartTime[FrontPartialCounter]);
                        ListOfFrontPartialsStartTime.RemoveAt(FrontPartialCounter);
                        --FrontPartialCounter;
                        PertinentFreeSpot = new TimeLine(PertinentFreeSpotStart, PertinentFreeSpotEnd);
                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();

                        BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                        BorderElementEnd = null;

                        LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy, Occupancy);
                        DateTime LatestTimeForBetterEarlierReferenceTime = PertinentFreeSpot.Start;
                        LastSubCalElementForEarlierReferenceTime = ((CompleteArranegement.Count < 1) || (CompleteArranegement == null) ? null : CompleteArranegement[CompleteArranegement.Count - 1]);
                        if (LowestCostArrangement.Count > 0)
                        {
                            if ((LowestCostArrangement[0].getCalendarEventRange.Start != PertinentFreeSpot.Start))//Pin SubEvents To Start
                            {//if the first element is not a partial Sub Cal Event element
                                FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);

                            }
                            else
                            {
                                FreeSpotUpdated = PertinentFreeSpot.CreateCopy();// new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                            }
                            EarliestReferenceTIme = PertinentFreeSpot.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;
                            SubCalendarEvent LastSubCalEvent = LowestCostArrangement[LowestCostArrangement.Count - 1];
                            LatestTimeForBetterEarlierReferenceTime = LastSubCalEvent.End;
                            LastSubCalElementForEarlierReferenceTime = LastSubCalEvent;
                            /*
                            Dictionary<string, double> AllValidNodes = CalendarEvent.DistanceToAllNodes(LastSubCalEvent.SubEvent_ID.getLevelID(0));
                            SubCalendarEvent AppendableEVent;
                            foreach (string eachstring in AllValidNodes.Keys)
                            {
                                if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(eachstring))
                                {
                                    AppendableEVent = CalendarIDAndNonPartialSubCalEvents[eachstring].ToList()[0].Value;//Assumes Theres Always an element
                                    

                                    if ((AppendableEVent.ActiveDuration <= (FreeBoundary.End - LastSubCalEvent.End)) && (!LowestCostArrangement.Contains(AppendableEVent)))
                                    {
                                        LowestCostArrangement.Add(AppendableEVent);
                                        CalendarIDAndNonPartialSubCalEvents[eachstring].Remove(AppendableEVent.ID);
                                        if (CalendarIDAndNonPartialSubCalEvents[eachstring].Count < 1)//checks if List is empty. Deletes keyValuepair if list is empty
                                        {
                                            CalendarIDAndNonPartialSubCalEvents.Remove(eachstring);
                                        }
                                        FreeSpotUpdated = new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End);
                                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                                        EarliestReferenceTIme = AppendableEVent.End;
                                        break;
                                    }
                                }
                            }*/
                        }


                        TimeLineUpdated = null;
                        TimeLineUpdated = ObtainBetterEarlierReferenceTime(LowestCostArrangement, CalendarIDAndNonPartialSubCalEvents, FreeBoundary.End - LatestTimeForBetterEarlierReferenceTime, EarliestReferenceTIme, new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End), LastSubCalElementForEarlierReferenceTime);
                        if (TimeLineUpdated != null)
                        {
                            LowestCostArrangement = TimeLineUpdated.Item2;
                            EarliestReferenceTIme = TimeLineUpdated.Item1;
                        }
                        
                        foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                        {
                            --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                            PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                            string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                            if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                            {
                                CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                                if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                                {
                                    CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                                }
                            }
                            if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                            {
                                PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                            }
                        }
                        CompleteArranegement.AddRange(LowestCostArrangement);
                    }
                }


                DateTime ReferenceEndTime = FreeBoundary.End;
                PertinentFreeSpot = new TimeLine(EarliestReferenceTIme, ReferenceEndTime);
                /*LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(null, null), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy);

                if (LowestCostArrangement.Count > 0)
                {
                    if (!(LowestCostArrangement[0].getCalendarEventRange.Start == PertinentFreeSpot.Start))//Pin SubEvents To Start
                    {//if the first element is not a partial Sub Cal Event element
                        FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                    }
                    else
                    {
                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();// new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                    }
                    EarliestReferenceTIme = FreeSpotUpdated.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;
                }*/
                BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                BorderElementEnd = null;

                LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy, Occupancy);
                LastSubCalElementForEarlierReferenceTime = ((CompleteArranegement.Count < 1) || (CompleteArranegement == null) ? null : CompleteArranegement[CompleteArranegement.Count - 1]);
                DateTime LimitForBetterEarlierReferencTime = EarliestReferenceTIme;
                FreeSpotUpdated = PertinentFreeSpot.CreateCopy();
                if (LowestCostArrangement.Count > 0)
                {
                    if ((LowestCostArrangement[0].getCalendarEventRange.Start != PertinentFreeSpot.Start))//Pin SubEvents To Start
                    {//if the first element is not a partial Sub Cal Event element
                        FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);

                    }
                    else
                    {
                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();// new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                        Utility.PinSubEventsToStart(LowestCostArrangement, PertinentFreeSpot);
                    }
                    EarliestReferenceTIme = PertinentFreeSpot.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;
                    SubCalendarEvent LastSubCalEvent = LowestCostArrangement[LowestCostArrangement.Count - 1];
                    LimitForBetterEarlierReferencTime=LastSubCalEvent.End;
                    LastSubCalElementForEarlierReferenceTime = LastSubCalEvent;
                    
                    
                    
                    /*
                    
                    
                    Dictionary<string, double> AllValidNodes = CalendarEvent.DistanceToAllNodes(LastSubCalEvent.SubEvent_ID.getLevelID(0));
                    SubCalendarEvent AppendableEVent;
                    foreach (string eachstring in AllValidNodes.Keys)
                    {
                        if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(eachstring))
                        {
                            AppendableEVent = CalendarIDAndNonPartialSubCalEvents[eachstring].ToList()[0].Value;//Assumes Theres Always an element

                            if ((AppendableEVent.ActiveDuration <= (FreeBoundary.End - LastSubCalEvent.End)) && (!LowestCostArrangement.Contains(AppendableEVent)))
                            {
                                LowestCostArrangement.Add(AppendableEVent);
                                CalendarIDAndNonPartialSubCalEvents[eachstring].Remove(AppendableEVent.ID);
                                if (CalendarIDAndNonPartialSubCalEvents[eachstring].Count < 1)//checks if List is empty. Deletes keyValuepair if list is empty
                                {
                                    CalendarIDAndNonPartialSubCalEvents.Remove(eachstring);
                                }
                                FreeSpotUpdated = new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                                EarliestReferenceTIme = AppendableEVent.End;
                                break;
                            }
                        }
                    }*/

                }
                TimeLineUpdated = null;
                TimeLineUpdated = ObtainBetterEarlierReferenceTime(LowestCostArrangement, CalendarIDAndNonPartialSubCalEvents, FreeBoundary.End - LimitForBetterEarlierReferencTime, EarliestReferenceTIme, new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End), LastSubCalElementForEarlierReferenceTime);
                if (TimeLineUpdated != null)
                {
                    LowestCostArrangement = TimeLineUpdated.Item2;
                    EarliestReferenceTIme = TimeLineUpdated.Item1;
                }


                foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                {
                    --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                    PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                    string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                    if(CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                    {
                        CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                        if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                        {
                            CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                        }
                    }

                    if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                    {
                        PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                    }
                }
                CompleteArranegement.AddRange(LowestCostArrangement);

            }






            List<mTuple<bool, SubCalendarEvent>> retValue = new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>();

            foreach (SubCalendarEvent eachSubCalendarEvent in CompleteArranegement)
            {
                PossibleEntries[eachSubCalendarEvent.ActiveDuration][eachSubCalendarEvent.ID].Item1 = true;
                retValue.Add(PossibleEntries[eachSubCalendarEvent.ActiveDuration][eachSubCalendarEvent.ID]);
            }

            //List<List<SubCalendarEvent>> unrestrictedValidCombinations = generateCombinationForDifferentEntries(CompatibleWithList, PossibleEntries);

            retValue = reAlignSubCalEvents(FreeBoundary, retValue);
            if (TotalEventsForThisTImeLine != retValue.Count)
            {
                ;
            }
            return retValue;

        }
Esempio n. 31
0
        public virtual void SetObjects(uint count, object[] punk)
        {
            if (punk == null)
            {
                return;
            }

            if (count > 0)
            {
                if (punk[0] is ProjectConfig)
                {
                    ArrayList configs = new ArrayList();

                    for (int i = 0; i < count; i++)
                    {
                        ProjectConfig config = (ProjectConfig)punk[i];

                        if (this.project == null || (this.project != (punk[0] as ProjectConfig).ProjectMgr))
                        {
                            this.project = config.ProjectMgr;
                        }

                        configs.Add(config);
                    }

                    this.projectConfigs = (ProjectConfig[])configs.ToArray(typeof(ProjectConfig));
                }
                else if (punk[0] is NodeProperties)
                {
                    if (this.project == null || (this.project != (punk[0] as NodeProperties).Node.ProjectMgr))
                    {
                        this.project = (punk[0] as NodeProperties).Node.ProjectMgr;
                    }

                    System.Collections.Generic.Dictionary <string, ProjectConfig> configsMap = new System.Collections.Generic.Dictionary <string, ProjectConfig>();

                    for (int i = 0; i < count; i++)
                    {
                        NodeProperties property = (NodeProperties)punk[i];
                        IVsCfgProvider provider;
                        ErrorHandler.ThrowOnFailure(property.Node.ProjectMgr.GetCfgProvider(out provider));
                        uint[] expected = new uint[1];
                        ErrorHandler.ThrowOnFailure(provider.GetCfgs(0, null, expected, null));
                        if (expected[0] > 0)
                        {
                            ProjectConfig[] configs = new ProjectConfig[expected[0]];
                            uint[]          actual  = new uint[1];
                            ErrorHandler.ThrowOnFailure(provider.GetCfgs(expected[0], configs, actual, null));

                            foreach (ProjectConfig config in configs)
                            {
                                if (!configsMap.ContainsKey(config.ConfigName))
                                {
                                    configsMap.Add(config.ConfigName, config);
                                }
                            }
                        }
                    }

                    if (configsMap.Count > 0)
                    {
                        if (this.projectConfigs == null)
                        {
                            this.projectConfigs = new ProjectConfig[configsMap.Keys.Count];
                        }
                        configsMap.Values.CopyTo(this.projectConfigs, 0);
                    }
                }
            }
            else
            {
                this.project = null;
            }

            if (this.active && this.project != null)
            {
                UpdateObjects();
            }
        }
Esempio n. 32
0
        private void FillData()
        {
            string[] array = this.m_devidsinRack.Split(new char[]
            {
                ','
            });
            System.Collections.Generic.Dictionary <int, ClientAPI.DeviceWithZoneRackInfo> devicRackZoneRelation = ClientAPI.GetDevicRackZoneRelation();
            this.treeView1.Nodes.Clear();
            string   text     = "";
            TreeNode treeNode = new TreeNode();

            treeNode.Name       = "Root";
            treeNode.ImageIndex = 1;
            this.treeView1.Nodes.Add(treeNode);
            this.treeView1.Indent = 15;
            DataSet dataSet = new DataSet();

            try
            {
                dataSet = this.allData;
                string[] array2 = array;
                for (int i = 0; i < array2.Length; i++)
                {
                    string text2 = array2[i];
                    int    num   = System.Convert.ToInt32(text2);
                    if (devicRackZoneRelation.ContainsKey(num))
                    {
                        ClientAPI.DeviceWithZoneRackInfo deviceWithZoneRackInfo = devicRackZoneRelation[num];
                        DataTable dataTable = dataSet.Tables[0].Clone();
                        DataRow[] array3    = dataSet.Tables[0].Select("device_id=" + text2);
                        for (int j = 0; j < array3.Length; j++)
                        {
                            dataTable.ImportRow(array3[j]);
                        }
                        if (dataTable.Rows.Count > 0 && this.m_UACDevPort.ContainsKey((long)num))
                        {
                            TreeNode treeNode2 = new TreeNode();
                            treeNode2.Name = "Device";
                            if (System.Convert.ToString(dataTable.Rows[0]["device_nm"]) != System.Convert.ToString(-1000))
                            {
                                if (System.Convert.ToString(dataTable.Rows[0]["device_nm"]) != "")
                                {
                                    treeNode2.Text = System.Convert.ToString(dataTable.Rows[0]["device_nm"]);
                                }
                                else
                                {
                                    treeNode2.Text = System.Convert.ToString(dataTable.Rows[0]["device_ip"]);
                                }
                            }
                            else
                            {
                                treeNode2.Text = "";
                            }
                            text = deviceWithZoneRackInfo.rack_nm;
                            if (System.Convert.ToString(dataTable.Rows[0]["device_state"]) != "1")
                            {
                                treeNode2.ImageIndex         = 6;
                                treeNode2.SelectedImageIndex = 6;
                                treeNode.Nodes.Add(treeNode2);
                            }
                            else
                            {
                                treeNode2.ImageIndex         = 7;
                                treeNode2.SelectedImageIndex = 7;
                                string         device_model      = deviceWithZoneRackInfo.device_model;
                                string         fw_version        = deviceWithZoneRackInfo.fw_version;
                                DevModelConfig deviceModelConfig = DevAccessCfg.GetInstance().getDeviceModelConfig(device_model, fw_version);
                                bool           flag = true;
                                if (this.m_UACDevPort.ContainsKey((long)num) && (this.m_UACDevPort[(long)num] == null || this.m_UACDevPort[(long)num].Count == 0))
                                {
                                    double   maxV        = ecoConvert.f2d(dataTable.Rows[0]["max_power"]);
                                    double   minV        = ecoConvert.f2d(dataTable.Rows[0]["min_power"]);
                                    double   maxV2       = ecoConvert.f2d(dataTable.Rows[0]["max_current"]);
                                    double   minV2       = ecoConvert.f2d(dataTable.Rows[0]["min_current"]);
                                    double   maxV3       = ecoConvert.f2d(dataTable.Rows[0]["max_voltage"]);
                                    double   minV3       = ecoConvert.f2d(dataTable.Rows[0]["min_voltage"]);
                                    double   maxV4       = ecoConvert.f2d(dataTable.Rows[0]["max_power_diss"]);
                                    double   minV4       = ecoConvert.f2d(dataTable.Rows[0]["min_power_diss"]);
                                    int      uIthEdidflg = devcfgUtil.UIThresholdEditFlg(deviceModelConfig, "dev");
                                    TreeNode treeNode3   = this.genTreeNode(uIthEdidflg, 4, EcoLanguage.getMsg(LangRes.Title_PowerDiss, new string[0]), ecoConvert.f2d(dataTable.Rows[0]["power_consumption"]), minV4, maxV4, "F4", "kWh", 13, 15, 14, 12, ref flag);
                                    if (treeNode3 != null)
                                    {
                                        treeNode2.Nodes.Add(treeNode3);
                                    }
                                    TreeNode treeNode4 = this.genTreeNode(uIthEdidflg, 3, EcoLanguage.getMsg(LangRes.Title_Power, new string[0]), ecoConvert.f2d(dataTable.Rows[0]["power_value"]), minV, maxV, "F4", "W", 13, 15, 14, 12, ref flag);
                                    if (treeNode4 != null)
                                    {
                                        treeNode2.Nodes.Add(treeNode4);
                                    }
                                    TreeNode treeNode5 = this.genTreeNode(uIthEdidflg, 2, EcoLanguage.getMsg(LangRes.Title_Voltage, new string[0]), ecoConvert.f2d(dataTable.Rows[0]["voltage_value"]), minV3, maxV3, "F2", "V", 25, 27, 26, 24, ref flag);
                                    if (treeNode5 != null)
                                    {
                                        treeNode2.Nodes.Add(treeNode5);
                                    }
                                    TreeNode treeNode6 = this.genTreeNode(uIthEdidflg, 1, EcoLanguage.getMsg(LangRes.Title_Current, new string[0]), ecoConvert.f2d(dataTable.Rows[0]["current_value"]), minV2, maxV2, "F2", "A", 3, 5, 4, 2, ref flag);
                                    if (treeNode6 != null)
                                    {
                                        treeNode2.Nodes.Add(treeNode6);
                                    }
                                    if (deviceModelConfig.leakCurrent == Constant.YES)
                                    {
                                        int num2 = (int)dataTable.Rows[0]["leakcurrent_status"];
                                        if (num2 == Constant.YES)
                                        {
                                            TreeNode treeNode7 = new TreeNode();
                                            treeNode7.Name               = "Neutral leakage current";
                                            treeNode7.ToolTipText        = treeNode7.Name;
                                            treeNode7.ImageIndex         = 35;
                                            treeNode7.SelectedImageIndex = 35;
                                            treeNode7.Text               = "Neutral leakage current";
                                            treeNode2.Nodes.Add(treeNode7);
                                            flag = false;
                                        }
                                    }
                                }
                                if (!flag)
                                {
                                    treeNode2.Expand();
                                }
                                if (this.m_UACDevPort.ContainsKey((long)num))
                                {
                                    this.FillData_Outlet(treeNode2, dataSet, text2, deviceModelConfig);
                                }
                                if (this.m_UACDevPort.ContainsKey((long)num) && (this.m_UACDevPort[(long)num] == null || this.m_UACDevPort[(long)num].Count == 0))
                                {
                                    this.FillData_Bank(treeNode2, dataSet, text2, deviceModelConfig);
                                }
                                if (this.m_UACDevPort.ContainsKey((long)num) && (this.m_UACDevPort[(long)num] == null || this.m_UACDevPort[(long)num].Count == 0))
                                {
                                    this.FillData_Line(treeNode2, dataSet, text2, deviceModelConfig);
                                }
                                treeNode.Nodes.Add(treeNode2);
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            treeNode.Text = text;
            treeNode.Expand();
        }
Esempio n. 33
0
 private static bool InternalAudioSamplesDelegate(uint playingID, float[] samples, uint channelIndex, uint frames)
 {
     return(audioSamplesDelegates.ContainsKey(playingID) &&
            audioSamplesDelegates[playingID](playingID, channelIndex, samples));
 }
Esempio n. 34
0
        public DataSet LoadFromDBEntity()
        {
            SqlConnection dbconn = new SqlConnection();

            dbconn.ConnectionString = DB.GetDBConn();
            dbconn.Open();

            SqlCommand cmd = new SqlCommand();

            cmd.Connection  = dbconn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "aspdnsf_GetProductsEntity";

            if (CategoryID != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@CategoryID", SqlDbType.Int));
                cmd.Parameters["@CategoryID"].Value = m_CategoryID;
            }

            if (SectionID != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@SectionID", SqlDbType.Int));
                cmd.Parameters["@SectionID"].Value = m_SectionID;
            }

            if (ManufacturerID != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@ManufacturerID", SqlDbType.Int));
                cmd.Parameters["@ManufacturerID"].Value = m_ManufacturerID;
            }

            if (DistributorID != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@distributorID", SqlDbType.Int));
                cmd.Parameters["@distributorID"].Value = m_DistributorID;
            }

            if (GenreID != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@genreID", SqlDbType.Int));
                cmd.Parameters["@genreID"].Value = m_GenreID;
            }

            if (VectorID != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@vectorID", SqlDbType.Int));
                cmd.Parameters["@vectorID"].Value = m_VectorID;
            }

            if (!AppLogic.IsAdminSite && AffiliateID != 0 && AppLogic.AppConfigBool("FilterProductsByAffiliate"))
            {
                cmd.Parameters.Add(new SqlParameter("@AffiliateID", SqlDbType.Int));
                cmd.Parameters["@AffiliateID"].Value = m_AffiliateID;
            }

            /**********************************
             * Modified by : mark
             * Date : 11.16.2006
             * No. : 97
             *********************************/
            // let's supply the product type as 0 to indicate
            // that don't want to filter by ProductType
            // which we will validate in the stored procedure


            cmd.Parameters.Add(new SqlParameter("@ProductTypeID", SqlDbType.Int));
            cmd.Parameters["@ProductTypeID"].Value = m_ProductTypeID;

            /****** end modification ****************/

            cmd.Parameters.Add(new SqlParameter("@ViewType", SqlDbType.Int));
            cmd.Parameters["@ViewType"].Value = CommonLogic.IIF(m_ReturnAllVariants || m_SearchMatch.Length != 0, 0, 1);

            cmd.Parameters.Add(new SqlParameter("@StatsFirst", SqlDbType.Int));
            cmd.Parameters["@StatsFirst"].Value = 0;

            if (m_SearchMatch.Length != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@SearchStr", SqlDbType.NVarChar));
                cmd.Parameters["@SearchStr"].Value = m_SearchMatch;
                cmd.Parameters.Add(new SqlParameter("@ExtSearch", SqlDbType.Int));
                cmd.Parameters["@ExtSearch"].Value = CommonLogic.IIF(m_SearchDescriptionAndSummaryFields, 1, 0);
            }

            cmd.Parameters.Add(new SqlParameter("@PublishedOnly", SqlDbType.Int));
            cmd.Parameters["@PublishedOnly"].Value = CommonLogic.IIF(m_PublishedOnly, 1, 0);

            cmd.Parameters.Add(new SqlParameter("@OnSaleOnly", SqlDbType.Int));
            cmd.Parameters["@OnSaleOnly"].Value = CommonLogic.IIF(m_OnSaleOnly, 1, 0);

            if (m_SearchIndex.Length != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@SearchIndex", SqlDbType.Char));
                cmd.Parameters["@SearchIndex"].Value = m_SearchIndex;
            }
            if (m_SortOrder.Length != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@SortOrder", SqlDbType.VarChar));
                cmd.Parameters["@SortOrder"].Value = (m_SortOrder.Length > 0 ? m_SortOrder : "ASC");
            }
            if (m_SortBy.Length != 0)
            {
                cmd.Parameters.Add(new SqlParameter("@SortBy", SqlDbType.VarChar));
                cmd.Parameters["@SortBy"].Value = (m_SortBy.Length > 0 ? m_SortBy : "Name");
            }

            m_Products = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(m_Products, "Table");
            dbconn.Close();

            DataRow PagingStatsRow = m_Products.Tables[1].Rows[0];

            m_NumPages = DB.RowFieldInt(PagingStatsRow, "Pages");

            System.Collections.Generic.Dictionary <int, bool> hTable = new System.Collections.Generic.Dictionary <int, bool>();

            foreach (DataRow drow in m_Products.Tables[0].Rows)
            {
                if (!hTable.ContainsKey((int)drow["ProductID"]))
                {
                    hTable.Add((int)drow["ProductID"], true);
                }
                else
                {
                    drow.Delete();
                }
            }
            m_Products.AcceptChanges();

            m_NumProducts = m_Products.Tables[0].Rows.Count;

            return(m_Products);
        }
        public void AddCommand()
        {
            try
            {
                if (string.IsNullOrEmpty(this.MenuName))
                {
                    // No menu required
                    return;
                }

                Command     cmdTmp;
                CommandBars cmdBars = (CommandBars)appObj.CommandBars;

                // Check any old versions of the command are not still hanging around
                try
                {
                    cmdTmp = appObj.Commands.Item(this.CommandName, UNKNOWN_CMD_ID);
                    cmdTmp.Delete();
                }
                catch { }

                // this is an empty array for passing into the AddNamedCommand method
                object[] contextUIGUIDs = null;

                cmdTmp = appObj.Commands.AddNamedCommand(
                    this.addIn,
                    this.GetType().Name,
                    this.ButtonText,
                    this.ToolTip,
                    true,
                    this.Bitmap,
                    ref contextUIGUIDs,
                    (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled);

                foreach (string sMenuName in this.MenuName.Split(','))
                {
                    CommandBar pluginCmdBar = null;

                    if (_cachedCommandBars.ContainsKey(sMenuName))
                    {
                        pluginCmdBar = _cachedCommandBars[sMenuName];
                    }
                    else
                    {
#if DENALI || SQL2014
                        //in VS2010, performance of cmdBars[sMenuName] is terrible: http://www.mztools.com/articles/2011/MZ2011005.aspx
                        //plus looking up cmdBars["Other Windows"] failsof the ones we're looking for are there
                        //performs better when you look at the root level of the CommandBars since most
                        foreach (CommandBar bar in cmdBars)
                        {
                            if (bar.Name == sMenuName)
                            {
                                pluginCmdBar = bar;
                                break;
                            }
                        }

                        //if not yet found, then recurse
                        if (pluginCmdBar == null)
                        {
                            foreach (CommandBar bar in cmdBars)
                            {
                                pluginCmdBar = RecurseCommandBarToFindCommandBarByName(bar, sMenuName);
                                if (pluginCmdBar != null)
                                {
                                    break;
                                }
                            }
                        }
#else
                        pluginCmdBar = cmdBars[sMenuName];
#endif
                    }

                    if (pluginCmdBar == null)
                    {
                        System.Windows.Forms.MessageBox.Show("Cannot get the " + this.MenuName + " menubar");
                    }
                    else
                    {
                        if (!_cachedCommandBars.ContainsKey(sMenuName))
                        {
                            _cachedCommandBars.Add(sMenuName, pluginCmdBar);
                        }


                        pluginCmd = cmdTmp;

                        CommandBarButton btn;
                        if (sMenuName == "Tools")
                        {
                            if (toolsCommandBarPopup == null)
                            {
                                toolsCommandBarPopup = (CommandBarPopup)pluginCmdBar.Controls.Add(MsoControlType.msoControlPopup, System.Type.Missing, System.Type.Missing, 1, true);
                                toolsCommandBarPopup.CommandBar.Name = "BIDSHelperToolsCommandBarPopup";
                                toolsCommandBarPopup.Caption         = "BIDS Helper";
                            }
                            btn = pluginCmd.AddControl(toolsCommandBarPopup.CommandBar, 1) as CommandBarButton;
                            SetCustomIcon(btn);
                            btn.BeginGroup = BeginMenuGroup;
                            toolsCommandBarPopup.Visible = true;
                        }
                        else if (AddCommandToMultipleMenus)
                        {
                            //note, this doesn't look recursively through command bars, so non-top level command bars like "Other Windows" won't work using this option
                            foreach (CommandBar bar in (CommandBars)(appObj.CommandBars))
                            {
                                if (bar.Name == sMenuName)
                                {
                                    if (!ShouldPositionAtEnd)
                                    {
                                        btn = pluginCmd.AddControl(bar, 1) as CommandBarButton;
                                    }
                                    else
                                    {
                                        btn = pluginCmd.AddControl(bar, bar.Controls.Count - 1) as CommandBarButton;
                                    }
                                    SetCustomIcon(btn);
                                    btn.BeginGroup = BeginMenuGroup;
                                }
                            }
                        }
                        else
                        {
                            if (!ShouldPositionAtEnd)
                            {
                                btn = pluginCmd.AddControl(pluginCmdBar, 1) as CommandBarButton;
                            }
                            else
                            {
                                btn = pluginCmd.AddControl(pluginCmdBar, pluginCmdBar.Controls.Count - 1) as CommandBarButton;
                            }
                            SetCustomIcon(btn);
                            btn.BeginGroup = BeginMenuGroup;
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                MessageBox.Show("Problem registering " + this.FullName + " command: " + e.Message + "\r\n" + e.StackTrace);
            }
        }
Esempio n. 36
0
        public static void Main()
        {
            /* NamedInt の使い方 */

            //もちろん、普通のintとして使えます。
            Square S = 1234;
            Piece  P = 5678;

            P++;             //++, --に対応しました。

            Console.WriteLine("S = {0}, P = {1}", S, P);

            //ifだって大丈夫です
            if (S == 1234)
            {
                Console.WriteLine("Sは1234です!");
            }

            //でも別物同士の代入はできません… ★下の行のコメントを外してみてください★
            //S = P;



            /* StrictNamedInt の使い方 */
            //暗黙の型変換が行われない場合以外は、NamedIntと同じですが…

            P = 2;              //前項より使いまわしです、普通のNamedIntです。
            StrictPiece PS = 2; //これが "Strict"なNamedIntです。

            //ただの実験用。
            int[] test = new int[16];

            //こちらは暗黙でintになりますが…
            test[P] = 1234;

            //Strict版は暗黙変換されません)★下の行のコメントを外してみてください★
            //		test[PS] = 1234;

            //もちろん、明示型変換はOKです。
            test[(int)PS] = 5678;



            /* StrictNamedInt と純粋intのみを受け入れる配列 */

            //ここでは、int[]の代わりを作成します。
            //宣言: StrictIndexerArray<配列の型, 受け入れるStrictNamedInt> = new StrictIndexerArray<配列の型>(サイズ, 受け入れるStrictNamedInt);

            ProjectDark.NamedInt.StrictIndexerArray <int, StrictPiece> SIA = new ProjectDark.NamedInt.StrictIndexerArray <int, StrictPiece>(16);   //要素数16のint配列
                SIA[PS] = 5678;                                                                                                                    //キャストすることなく、配列添え字にできます。
            SIA[0] = 1234;                                                                                                                         //純粋intもいけます。

            //SIA[P} = 9012; //指定以外のStrictNamedはもちろん、NamedIntもだめです。★コメントを外してみてください★
            //ただし、コンパイルエラーが「型の違いを表すもの」ではなく「文法が間違っているもの」として表示されてしまうので分かりにくいいです。

            //Lengthや、
            System.Console.WriteLine("配列の長さ: {0}", SIA.Length);

            //foreachもそのまま使えます
            System.Console.Write("配列の中身: ");
            foreach (int Nakami in SIA)
            {
                System.Console.Write("{0}, ", Nakami);
            }
            System.Console.WriteLine("以上。");

            //Sort (IComparable)や、IConvertibleも利用できます。
            System.Collections.Generic.List <StrictPiece> keyList = new System.Collections.Generic.List <StrictPiece>();
            keyList.Add(123);
            keyList.Add(456);
            keyList.Sort();             //一応ソートしとく?

            //関数の引数が純粋なArrayしか受け付けない場合はキャストしてしまえばOKです。
            Array A = (Array)SIA;


            //ハッシュテーブルのキーとして使うテスト
            System.Collections.Hashtable H = new System.Collections.Hashtable();
            H.Add((StrictPiece)1, 1);
            H.Add(1, 1);
            Console.WriteLine("Hashtable: {0}", H.ContainsKey((StrictPiece)1));
            Console.WriteLine("Hashtable: {0}", H.ContainsKey(1));

            //Generics版Dicrionaryで使ってみる
            var Dict = new System.Collections.Generic.Dictionary <StrictPiece, StrictPiece>();

            Dict.Add((StrictPiece)1, (StrictPiece)111);
            Dict.Add((StrictPiece)2, (StrictPiece)12);
            Console.WriteLine("Dictionary: {0}", Dict.ContainsKey((StrictPiece)1));


            //intとのif()
            StrictPiece IFTEST_SI  = 1234;
            int         IFTEST_INT = 1234;

            if ((int)IFTEST_SI == IFTEST_INT)
            {
                Console.WriteLine("IfTest: True");
            }
            else
            {
                Console.WriteLine("IfTest: False");
            }
            if ((int)IFTEST_SI != IFTEST_INT)
            {
                Console.WriteLine("IfTest: True");
            }
            else
            {
                Console.WriteLine("IfTest: False");
            }

            if (IFTEST_SI == (StrictPiece)IFTEST_INT)
            {
                Console.WriteLine("IfTest2: True");
            }
            else
            {
                Console.WriteLine("IfTest2: False");
            }
            if (IFTEST_SI != (StrictPiece)IFTEST_INT)
            {
                Console.WriteLine("IfTest2: True");
            }
            else
            {
                Console.WriteLine("IfTest2: False");
            }


            //StrictNamedString (非サポート)
            StrictMeg M = "テスト文字列";

            Console.WriteLine(M);

            //		Console.WriteLine("{0}", X.Equals(X));

#if BUILD_VS
            System.Console.WriteLine("*: Press Enter to exit.");
            System.Console.ReadLine();             //VSビルド時、Enter待ちさせる(簡易)
#endif
        }
        // 得到销售订单dto
        /// <summary>
        /// 得到销售订单dto
        /// </summary>
        /// <param name="bpObj"></param>
        /// <returns></returns>
        private System.Collections.Generic.List <SaleOrderDTOData> GetSaleOrderDTODataList(CreateApprovedSaleOrderSV bpObj, out List <SO> lstExist)
        {
            lstExist = new List <SO>();

            System.Collections.Generic.List <SaleOrderDTOData> list = new System.Collections.Generic.List <SaleOrderDTOData>();
            System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <SoLineDTO> > dic = new System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <SoLineDTO> >();
            foreach (SoLineDTO solinedto in bpObj.SoLineDto)
            {
                if (!dic.ContainsKey(solinedto.SpitOrderFlag))
                {
                    dic.Add(solinedto.SpitOrderFlag, new System.Collections.Generic.List <SoLineDTO>());
                }
                dic[solinedto.SpitOrderFlag].Add(solinedto);
            }
            foreach (string key in dic.Keys)
            {
                List <SoLineDTO> listLineDTO = dic[key];

                if (listLineDTO != null &&
                    listLineDTO.Count > 0
                    )
                {
                    SoLineDTO firstDTO = listLineDTO.GetFirst <SoLineDTO>();

                    SO so = SO.Finder.Find("DescFlexField.PubDescSeg5=@DmsSaleNum"
                                           , new OqlParam(firstDTO.DmsSaleNo)
                                           );

                    // 订单存在,添加到订单清单里
                    if (so != null)
                    {
                        lstExist.Add(so);
                    }
                    //
                    else
                    {
                        SaleOrderDTOData sodto = new SaleOrderDTOData();
                        sodto.DocumentType      = (new CommonArchiveDataDTOData());
                        sodto.DocumentType.Code = (firstDTO.OrderType);
                        sodto.OrderBy           = (new CustomerMISCInfoData());
                        sodto.OrderBy.Code      = (firstDTO.DealerCode);
                        sodto.SOSrcType         = (SOSourceTypeEnum.Manual.Value);
                        sodto.TC = (new CommonArchiveDataDTOData());
                        //sodto.TC.Code = (string.IsNullOrEmpty(firstDTO.Currency) ? "C001" : firstDTO.Currency);
                        sodto.TC.Code                   = (string.IsNullOrEmpty(firstDTO.Currency) ? HBHCommon.DefaultCurrencyCode : firstDTO.Currency);
                        sodto.DescFlexField             = (new DescFlexSegmentsData());
                        sodto.DescFlexField.PubDescSeg5 = (firstDTO.DmsSaleNo);
                        //string RecTerm = "01";
                        string   RecTerm  = HBHCommon.DefaultRecTermCode;
                        Customer customer = Customer.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID, firstDTO.DealerCode), new OqlParam[0]);

                        sodto.SaleDepartment = new CommonArchiveDataDTOData();
                        sodto.Seller         = new CommonArchiveDataDTOData();
                        if (customer != null)
                        {
                            sodto.ConfirmTerm = (new CommonArchiveDataDTOData());
                            if (customer.ARConfirmTerm != null)
                            {
                                sodto.ConfirmTerm.Code = (customer.ARConfirmTerm.Code);
                            }
                            else
                            {
                                sodto.ConfirmTerm.Code = HBHCommon.DefaultConfirmTermCode;  // ("01");
                            }
                            sodto.BargainMode = (customer.Bargain.Value);
                            sodto.ShipRule    = (new CommonArchiveDataDTOData());
                            if (customer.ShippmentRuleKey != null)
                            {
                                sodto.ShipRule.Code = (customer.ShippmentRule.Code);
                            }
                            else
                            {
                                sodto.ShipRule.Code = HBHCommon.DefaultShipRuleCode;    // ("C001");
                            }
                            if (customer.RecervalTermKey != null)
                            {
                                RecTerm = customer.RecervalTerm.Code;
                            }

                            if (customer.SaleserKey != null)
                            {
                                sodto.Seller.ID = customer.SaleserKey.ID;
                                //Operators opeator = Operators.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), HBHCommon.DefaultShipOperatorCode), new OqlParam[0]);
                                //if (opeator != null)
                                //{
                                //    shipdto.SaleDept.ID = (opeator.DeptKey.ID);
                                //}
                            }
                            if (customer.DepartmentKey != null)
                            {
                                sodto.SaleDepartment.ID = customer.DepartmentKey.ID;
                            }
                        }
                        else
                        {
                            sodto.ShipRule.Code    = HBHCommon.DefaultShipRuleCode;    // ("C001");
                            sodto.BargainMode      = HBHCommon.DefaultBargainMode;     // (0);
                            sodto.ConfirmTerm      = (new CommonArchiveDataDTOData());
                            sodto.ConfirmTerm.Code = HBHCommon.DefaultConfirmTermCode; // ("01");
                        }
                        sodto.SOLines = new List <ISV.SM.SOLineDTOData>();
                        foreach (SoLineDTO srcsolinedto in dic[key])
                        {
                            UFIDA.U9.ISV.SM.SOLineDTOData solinedto2 = new UFIDA.U9.ISV.SM.SOLineDTOData();
                            solinedto2.ItemInfo          = (new ItemInfoData());
                            solinedto2.ItemInfo.ItemCode = (srcsolinedto.ErpMaterialCode);
                            if (!string.IsNullOrEmpty(srcsolinedto.FinalPrice))
                            {
                                solinedto2.FinallyPriceTC = (decimal.Parse(srcsolinedto.FinalPrice));
                            }
                            if (!string.IsNullOrEmpty(srcsolinedto.Number))
                            {
                                solinedto2.OrderByQtyPU = (decimal.Parse(srcsolinedto.Number));
                            }
                            else
                            {
                                solinedto2.OrderByQtyPU = (1m);
                            }
                            if (!string.IsNullOrEmpty(srcsolinedto.Money))
                            {
                                solinedto2.TotalMoneyTC = (decimal.Parse(srcsolinedto.Money));
                            }
                            solinedto2.Project       = (new CommonArchiveDataDTOData());
                            solinedto2.Project.Code  = (srcsolinedto.DmsSaleNo);
                            solinedto2.SrcDocType    = (SOSourceTypeEnum.Manual.Value);
                            solinedto2.RecTerm       = (new CommonArchiveDataDTOData());
                            solinedto2.RecTerm.Code  = (RecTerm);
                            solinedto2.DescFlexField = (new DescFlexSegmentsData());
                            solinedto2.DescFlexField.PrivateDescSeg1 = (srcsolinedto.MaterialCode);
                            solinedto2.SOShiplines = (new System.Collections.Generic.List <SOShipLineDTOData>());
                            SOShipLineDTOData soshipliendto = new SOShipLineDTOData();
                            soshipliendto.Project           = (new CommonArchiveDataDTOData());
                            soshipliendto.Project.Code      = (srcsolinedto.DmsSaleNo);
                            soshipliendto.ItemInfo          = (new ItemInfoData());
                            soshipliendto.ItemInfo.ItemCode = (srcsolinedto.ErpMaterialCode);
                            soshipliendto.IsMRPRequire      = (true);
                            soshipliendto.RequireDate       = (string.IsNullOrEmpty(srcsolinedto.DeliveryDate) ? System.DateTime.Now : System.Convert.ToDateTime(srcsolinedto.DeliveryDate));
                            solinedto2.SOShiplines.Add(soshipliendto);
                            sodto.SOLines.Add(solinedto2);
                        }
                        list.Add(sodto);
                    }
                }
            }
            return(list);
        }
Esempio n. 38
0
        public static void Run(string[] args)
        {
            try
            {
                var sourcefile = args.GetParameter("source", true);
                var targetfile = args.GetParameter("output", true);
                var forms      = Kipon.WebResources.Tools.Generator.Config.forms.GetFromXmlFile(sourcefile);

                IOrganizationService service = Kipon.WebResources.Tools.Service.Factory.GetOrganizationService(args);

                using (var uow = new Entities.CrmUnitOfWork(service))
                {
                    using (var writer = new CodeWriter(targetfile))
                    {
                        writer.Writeline("/// <reference path=\"xrm.d.ts\" />");
                        writer.Writeline("");
                        writer.Writeline("declare namespace XrmForm {");
                        foreach (var form in forms.form)
                        {
                            var xrmEntityForm = (from f in uow.Systemforms.GetQuery()
                                                 where f.ObjectTypeCode == form.entity &&
                                                 f.Name == form.name
                                                 select f).SingleOrDefault();

                            if (xrmEntityForm == null)
                            {
                                Console.WriteLine("Entity " + form.entity + " Form " + form.name + " was not found");
                                continue;
                            }

                            Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse entity = null;
                            if (entities.ContainsKey(form.entity))
                            {
                                entity = entities[form.entity];
                            }
                            else
                            {
                                var req = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest
                                {
                                    RetrieveAsIfPublished = true,
                                    LogicalName           = form.entity,
                                    EntityFilters         = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes
                                };
                                entity = uow.ExecuteRequest <Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse>(req);
                                entities.Add(form.entity, entity);
                            }

                            #region XrmForm interface
                            writer.Writeline("interface " + form.asname + " {");

                            var reader     = new System.IO.StringReader(xrmEntityForm.FormXml);
                            var serializer = new XmlSerializer(typeof(Kipon.WebResources.Tools.Generator.Xrm.form));

                            var xrmform = (Kipon.WebResources.Tools.Generator.Xrm.form)serializer.Deserialize(reader);

                            WriteFormControls(writer, entity, xrmform, true);

                            writer.Writeline("ui: " + form.asname + "UI;");
                            writer.Writeline("}");
                            #endregion

                            #region entity ui interface
                            writer.Writeline("interface " + form.asname + "UI {");
                            writer.Writeline("controls: " + form.asname + "UIControls;");
                            writer.Writeline("tabs: " + form.asname + "UITabs;");
                            writer.Writeline("}");
                            #endregion

                            #region controls
                            writer.Writeline("interface " + form.asname + "UIControls  {");
                            WriteFormControls(writer, entity, xrmform, false);
                            writer.Writeline("}");
                            #endregion

                            #region generate tabs
                            writer.Writeline("interface " + form.asname + "UITabs  {");
                            writer.Writeline("get(name: string): void;");
                            var ix = 0;
                            foreach (var tab in xrmform.tabs)
                            {
                                writer.Writeline("get(name: \"" + tab.name + "\"): " + form.asname + "UITab" + ix.ToString() + ";");
                                ix++;
                            }
                            writer.Writeline("}");

                            ix = 0;
                            foreach (var tab in xrmform.tabs)
                            {
                                writer.Writeline("interface " + form.asname + "UITab" + ix + " extends Xrm.Controls.UiStandardElement, Xrm.Controls.UiFocusable {");
                                writer.Writeline("sections: " + form.asname + "UITab" + ix + "Sections;");
                                writer.Writeline("}");
                                ix++;
                            }

                            ix = 0;
                            foreach (var tab in xrmform.tabs)
                            {
                                writer.Writeline("interface " + form.asname + "UITab" + ix + "Sections {");
                                writer.Writeline("get(name: string): void;");

                                foreach (var col in tab.columns)
                                {
                                    foreach (var sec in col.sections)
                                    {
                                        writer.Writeline("get(name: \"" + sec.name + "\"): Xrm.Controls.Section;");
                                    }
                                }
                                writer.Writeline("}");
                                ix++;
                            }
                            #endregion
                        }
                        writer.Writeline("}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                Console.WriteLine("Usage: Kipon.WebResources.Tools generate /url:url /user:user /password:password /source:definitionsourcefilename /output:output.d.name");
            }
        }
Esempio n. 39
0
        public virtual bool ContainsRelationship(Net.Vpc.Upa.Relationship item)
        {
            string s = item.GetName();

            return(relations.ContainsKey(s));
        }
Esempio n. 40
0
        static void Main(string[] args)
        {
            Serilog.Log.Logger = new Serilog.LoggerConfiguration()
                                 .MinimumLevel.Debug()
                                 .WriteTo.Console(outputTemplate:
                                                  "[{Timestamp:yyyy-MM-dd - HH:mm:ss}] [{SourceContext:s}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
                                 .CreateLogger();

            var service = Service.createService(args[0]);

            Filecontainer.target_dir = service.files_targetpath;

            msbClient               = new Fraunhofer.IPA.MSB.Client.Websocket.MsbClient(service.target_interface);
            msbClient.Connected    += msbCallback_Connected;
            msbClient.Disconnected += msbCallback_Disconnected;
            msbClient.Registered   += msbCallback_Registered;
            msbClient.AutoReconnect = true;
            msbClient.AutoReconnectIntervalInMilliseconds = 10000;

            msbApplication = new Fraunhofer.IPA.MSB.Client.API.Model.Application(service.uuid, service.name, service.description, service.token);

            fileEvent = new Fraunhofer.IPA.MSB.Client.API.Model.Event("fEv", "FileEvent", "File event", typeof(FileObject));
            msbApplication.AddEvent(fileEvent);

            var filecontainer = new Filecontainer();

            var methodInfo      = filecontainer.GetType().GetMethod("receiveFile");
            var receiveFunction = new Fraunhofer.IPA.MSB.Client.API.Model.Function("fF", "FileFunction", "File function", methodInfo, filecontainer);

            msbApplication.AddFunction(receiveFunction);

            msbClient.ConnectAsync();

            System.Collections.Generic.Dictionary <string, System.IO.FileInfo> oldFiles = new System.Collections.Generic.Dictionary <string, System.IO.FileInfo>();
            var newFiles = new System.Collections.Generic.Dictionary <string, System.IO.FileInfo>();

            try {
                var oldstatus = System.IO.File.ReadAllText(service.files_sourcepath + "/oldfiles.json");
                oldFiles = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.Generic.Dictionary <string, System.IO.FileInfo> >(oldstatus);
            } catch {
                oldFiles = new System.Collections.Generic.Dictionary <string, System.IO.FileInfo>();
            }

            while (!msbActive)
            {
                System.Threading.Thread.Sleep(5000);
            }

            while (true)
            {
                var fileInfos = new System.IO.DirectoryInfo(service.files_sourcepath).GetFiles();

                foreach (var fileInfo in fileInfos)
                {
                    if (!newFiles.ContainsKey(fileInfo.Name))
                    {
                        if (oldFiles.ContainsKey(fileInfo.Name))
                        {
                            if (oldFiles[fileInfo.Name].LastWriteTime >= fileInfo.LastWriteTime)
                            {
                                continue;
                            }
                        }
                        newFiles.Add(fileInfo.Name, fileInfo);
                    }
                }

                if (msbActive)
                {
                    var toRemove = new System.Collections.Generic.List <string>();
                    foreach (var newFile in newFiles)
                    {
                        var file = new File(newFile.Value.FullName, service.file_splitting_length);
                        var fileEventInstance = new Fraunhofer.IPA.MSB.Client.API.Model.EventData(fileEvent);

                        foreach (var d_ in file.fileObjects)
                        {
                            fileEventInstance.Value = d_;
                            msbClient.PublishAsync(msbApplication, fileEventInstance);
                            System.Threading.Thread.Sleep(100);
                        }

                        toRemove.Add(newFile.Key);

                        if (!msbActive)
                        {
                            break;
                        }
                    }

                    foreach (var rem in toRemove)
                    {
                        oldFiles.Add(rem, newFiles[rem]);
                        newFiles.Remove(rem);
                    }

                    if (toRemove.Count > 0)
                    {
                        var status = Newtonsoft.Json.JsonConvert.SerializeObject(oldFiles);
                        System.IO.File.WriteAllText(service.files_sourcepath + "/oldfiles.json", status);
                    }
                }

                filecontainer.clearByTimelimit(service.file_timelimit);

                while (!msbActive)
                {
                    System.Threading.Thread.Sleep(10000);
                }
            }
        }
Esempio n. 41
0
        private void btnImport_Click(object sender, System.EventArgs e)
        {
            string text = this.dropFiles.SelectedValue;

            text = System.IO.Path.Combine(this._dataPath, text);
            if (!System.IO.File.Exists(text))
            {
                this.ShowMsg("选择的数据包文件有问题!", false);
                return;
            }
            int num  = 0;
            int num2 = 0;

            this.PrepareDataFiles(new object[]
            {
                text
            });
            System.Collections.Generic.List <System.Collections.Generic.List <string> > list = this.ReadCsv(this.csvPath, true, '\t', System.Text.Encoding.GetEncoding("GB2312"));
            int i     = 0;
            int count = list.Count;

            while (i < count)
            {
                ProductInfo productInfo = new ProductInfo();
                try
                {
                    System.Collections.Generic.List <string> list2 = list[i];
                    if (list2[18] != "")
                    {
                        System.Data.DataTable brandCategories = CatalogHelper.GetBrandCategories(list2[18]);
                        if (brandCategories.Rows.Count > 0)
                        {
                            productInfo.BrandId = new int?(System.Convert.ToInt32(brandCategories.Rows[0]["BrandId"]));
                        }
                    }
                    if (list2[1] != "")
                    {
                        System.Data.DataTable categoryes = CatalogHelper.GetCategoryes(list2[1]);
                        if (categoryes.Rows.Count > 0)
                        {
                            productInfo.CategoryId = System.Convert.ToInt32(categoryes.Rows[0]["CategoryId"]);
                        }
                        else
                        {
                            productInfo.CategoryId = 0;
                        }
                    }
                    else
                    {
                        productInfo.CategoryId = 0;
                    }
                    if (list2[7] != "")
                    {
                        string path = System.IO.Path.Combine(this.csvPath.Replace(".csv", ""), list2[7]);
                        using (System.IO.StreamReader streamReader = new System.IO.StreamReader(path, System.Text.Encoding.GetEncoding("gb2312")))
                        {
                            productInfo.Description = streamReader.ReadToEnd();
                        }
                    }
                    if (productInfo.CategoryId > 0)
                    {
                        productInfo.MainCategoryPath = CatalogHelper.GetCategory(productInfo.CategoryId).Path + "|";
                    }
                    productInfo.HasSKU    = (int.Parse(list2[19]) == 1);
                    productInfo.ImageUrl1 = "";
                    productInfo.ImageUrl2 = "";
                    productInfo.ImageUrl3 = "";
                    productInfo.ImageUrl4 = "";
                    productInfo.ImageUrl5 = "";
                    if (list2[12] != "")
                    {
                        System.IO.FileInfo fileInfo = new System.IO.FileInfo(System.IO.Path.Combine(this.csvPath.Replace(".csv", ""), list2[12]));
                        if (fileInfo.Exists)
                        {
                            this.GetImg(fileInfo.FullName, ref productInfo, 1);
                        }
                    }
                    if (list2[13] != "")
                    {
                        System.IO.FileInfo fileInfo2 = new System.IO.FileInfo(System.IO.Path.Combine(this.csvPath.Replace(".csv", ""), list2[13]));
                        if (fileInfo2.Exists)
                        {
                            this.GetImg(fileInfo2.FullName, ref productInfo, 2);
                        }
                    }
                    if (list2[14] != "")
                    {
                        System.IO.FileInfo fileInfo3 = new System.IO.FileInfo(System.IO.Path.Combine(this.csvPath.Replace(".csv", ""), list2[14]));
                        if (fileInfo3.Exists)
                        {
                            this.GetImg(fileInfo3.FullName, ref productInfo, 3);
                        }
                    }
                    if (list2[15] != "")
                    {
                        System.IO.FileInfo fileInfo4 = new System.IO.FileInfo(System.IO.Path.Combine(this.csvPath.Replace(".csv", ""), list2[15]));
                        if (fileInfo4.Exists)
                        {
                            this.GetImg(fileInfo4.FullName, ref productInfo, 4);
                        }
                    }
                    if (list2[16] != "")
                    {
                        System.IO.FileInfo fileInfo5 = new System.IO.FileInfo(System.IO.Path.Combine(this.csvPath.Replace(".csv", ""), list2[16]));
                        if (fileInfo5.Exists)
                        {
                            this.GetImg(fileInfo5.FullName, ref productInfo, 5);
                        }
                    }
                    if (list2[17] != "")
                    {
                        productInfo.MarketPrice = new decimal?(decimal.Parse(list2[17]));
                    }
                    if (list2[9] != "")
                    {
                        productInfo.MetaDescription = list2[9];
                    }
                    if (list2[10] != "")
                    {
                        productInfo.MetaKeywords = list2[10];
                    }
                    if (list2[4] != "")
                    {
                        productInfo.ProductCode = list2[4];
                    }
                    productInfo.ProductName = list2[3];
                    string text2 = list2[11];
                    string a;
                    if ((a = text2) != null)
                    {
                        if (!(a == "出售中"))
                        {
                            if (!(a == "下架区"))
                            {
                                if (a == "仓库中")
                                {
                                    productInfo.SaleStatus = ProductSaleStatus.OnStock;
                                }
                            }
                            else
                            {
                                productInfo.SaleStatus = ProductSaleStatus.UnSale;
                            }
                        }
                        else
                        {
                            productInfo.SaleStatus = ProductSaleStatus.OnSale;
                        }
                    }
                    if (list2[5] != "")
                    {
                        productInfo.ShortDescription = list2[5];
                    }
                    if (list2[8] != "")
                    {
                        productInfo.Title = list2[8];
                    }
                    if (list2[2] != "")
                    {
                        int typeId = ProductTypeHelper.GetTypeId(list2[2]);
                        if (typeId > 0)
                        {
                            productInfo.TypeId = new int?(typeId);
                        }
                    }
                    if (!productInfo.TypeId.HasValue)
                    {
                        productInfo.HasSKU = false;
                    }
                    if (list2[6] != "")
                    {
                        productInfo.Unit = list2[6];
                    }
                    System.Collections.Generic.Dictionary <string, SKUItem> dictionary = null;
                    System.Collections.Generic.Dictionary <int, System.Collections.Generic.IList <int> > dictionary2 = null;
                    System.Collections.Generic.IList <int> list3 = new System.Collections.Generic.List <int>();
                    if (list2[20] == "")
                    {
                        dictionary = new System.Collections.Generic.Dictionary <string, SKUItem>();
                        SKUItem sKUItem = new SKUItem();
                        sKUItem.SkuId     = "0";
                        sKUItem.CostPrice = decimal.Parse(list2[24].Split(new char[]
                        {
                            ';'
                        })[0]);
                        sKUItem.SalePrice = decimal.Parse(list2[25].Split(new char[]
                        {
                            ';'
                        })[0]);
                        sKUItem.SKU = list2[21].Split(new char[]
                        {
                            ';'
                        })[0];
                        sKUItem.Stock = int.Parse(list2[23].Split(new char[]
                        {
                            ';'
                        })[0]);
                        sKUItem.Weight = decimal.Parse(list2[22].Split(new char[]
                        {
                            ';'
                        })[0]);
                        dictionary.Add(sKUItem.SKU, sKUItem);
                    }
                    else
                    {
                        if (productInfo.TypeId.HasValue)
                        {
                            dictionary = new System.Collections.Generic.Dictionary <string, SKUItem>();
                            int value = productInfo.TypeId.Value;
                            if (productInfo.HasSKU)
                            {
                                ProductTypeHelper.GetAttributes(value, AttributeUseageMode.Choose);
                                string[] array = list2[20].Split(new char[]
                                {
                                    ';'
                                });
                                int num3 = array.Length;
                                for (int j = 0; j < num3; j++)
                                {
                                    SKUItem sKUItem2 = new SKUItem();
                                    sKUItem2.CostPrice = decimal.Parse(list2[24].Split(new char[]
                                    {
                                        ';'
                                    })[j]);
                                    sKUItem2.SalePrice = decimal.Parse(list2[25].Split(new char[]
                                    {
                                        ';'
                                    })[j]);
                                    sKUItem2.SKU = list2[21].Split(new char[]
                                    {
                                        ';'
                                    })[j];
                                    sKUItem2.Stock = int.Parse(list2[23].Split(new char[]
                                    {
                                        ';'
                                    })[j]);
                                    sKUItem2.Weight = decimal.Parse(list2[22].Split(new char[]
                                    {
                                        ';'
                                    })[j]);
                                    string text3 = array[j];
                                    System.Collections.Generic.Dictionary <int, int> dictionary3 = new System.Collections.Generic.Dictionary <int, int>();
                                    string[] array2 = text3.Split(new char[]
                                    {
                                        ','
                                    });
                                    for (int k = 0; k < array2.Length; k++)
                                    {
                                        string text4             = array2[k];
                                        string specificationName = text4.Split(new char[]
                                        {
                                            ':'
                                        })[0];
                                        string valueStr = text4.Split(new char[]
                                        {
                                            ':'
                                        })[1];
                                        int specificationId = ProductTypeHelper.GetSpecificationId(value, specificationName);
                                        if (specificationId <= 0)
                                        {
                                            productInfo.HasSKU = false;
                                            break;
                                        }
                                        int specificationValueId = ProductTypeHelper.GetSpecificationValueId(specificationId, valueStr);
                                        if (specificationValueId <= 0)
                                        {
                                            productInfo.HasSKU = false;
                                            break;
                                        }
                                        dictionary3.Add(specificationId, specificationValueId);
                                    }
                                    if (productInfo.HasSKU && dictionary3.Count > 0)
                                    {
                                        string text5 = "";
                                        foreach (System.Collections.Generic.KeyValuePair <int, int> current in dictionary3)
                                        {
                                            sKUItem2.SkuItems.Add(current.Key, current.Value);
                                            text5 = text5 + current.Value + "_";
                                        }
                                        sKUItem2.SkuId = text5.Substring(0, text5.Length - 1);
                                        dictionary.Add(sKUItem2.SKU, sKUItem2);
                                    }
                                }
                                if (dictionary.Count > 0)
                                {
                                    productInfo.HasSKU = true;
                                }
                            }
                            else
                            {
                                SKUItem sKUItem3 = new SKUItem();
                                sKUItem3.SkuId     = "0";
                                sKUItem3.CostPrice = decimal.Parse(list2[24].Split(new char[]
                                {
                                    ';'
                                })[0]);
                                sKUItem3.SalePrice = decimal.Parse(list2[25].Split(new char[]
                                {
                                    ';'
                                })[0]);
                                sKUItem3.SKU = list2[21].Split(new char[]
                                {
                                    ';'
                                })[0];
                                sKUItem3.Stock = int.Parse(list2[23].Split(new char[]
                                {
                                    ';'
                                })[0]);
                                sKUItem3.Weight = int.Parse(list2[22].Split(new char[]
                                {
                                    ';'
                                })[0]);
                                dictionary.Add(sKUItem3.SKU, sKUItem3);
                            }
                        }
                    }
                    if (list2[26] != "" && productInfo.TypeId.HasValue)
                    {
                        int value2 = productInfo.TypeId.Value;
                        dictionary2 = new System.Collections.Generic.Dictionary <int, System.Collections.Generic.IList <int> >();
                        System.Collections.Generic.IList <AttributeInfo> attributes = ProductTypeHelper.GetAttributes(value2, AttributeUseageMode.View);
                        foreach (AttributeInfo current2 in ProductTypeHelper.GetAttributes(value2, AttributeUseageMode.MultiView))
                        {
                            attributes.Add(current2);
                        }
                        string[] array2 = list2[26].Split(new char[]
                        {
                            ','
                        });
                        for (int k = 0; k < array2.Length; k++)
                        {
                            string text6  = array2[k];
                            string value3 = text6.Split(new char[]
                            {
                                ':'
                            })[0];
                            string valueStr2 = text6.Split(new char[]
                            {
                                ':'
                            })[1];
                            bool flag = false;
                            int  num4 = 0;
                            foreach (AttributeInfo current3 in attributes)
                            {
                                if (current3.AttributeName.Equals(value3))
                                {
                                    num4 = current3.AttributeId;
                                    flag = true;
                                    break;
                                }
                            }
                            if (flag)
                            {
                                int specificationValueId2 = ProductTypeHelper.GetSpecificationValueId(num4, valueStr2);
                                if (specificationValueId2 > 0)
                                {
                                    if (dictionary2.ContainsKey(num4))
                                    {
                                        dictionary2[num4].Add(specificationValueId2);
                                    }
                                    else
                                    {
                                        dictionary2.Add(num4, new System.Collections.Generic.List <int>
                                        {
                                            specificationValueId2
                                        });
                                    }
                                }
                            }
                        }
                    }
                    if (list2[27] != "")
                    {
                        list3 = new System.Collections.Generic.List <int>();
                        System.Data.DataTable tags = CatalogHelper.GetTags();
                        string[] array2            = list2[27].Split(new char[]
                        {
                            ','
                        });
                        for (int k = 0; k < array2.Length; k++)
                        {
                            string obj = array2[k];
                            foreach (System.Data.DataRow dataRow in tags.Rows)
                            {
                                if (dataRow["TagName"].Equals(obj))
                                {
                                    list3.Add(System.Convert.ToInt32(dataRow["TagId"]));
                                    break;
                                }
                            }
                        }
                    }
                    productInfo.AddedDate = System.DateTime.Now;
                    ProductActionStatus productActionStatus = ProductHelper.AddProduct(productInfo, dictionary, dictionary2, list3);
                    if (productActionStatus == ProductActionStatus.Success)
                    {
                        num++;
                    }
                    else
                    {
                        if (productActionStatus == ProductActionStatus.AttributeError)
                        {
                            num2++;
                        }
                        else
                        {
                            if (productActionStatus == ProductActionStatus.DuplicateName)
                            {
                                num2++;
                            }
                            else
                            {
                                if (productActionStatus == ProductActionStatus.DuplicateSKU)
                                {
                                    num2++;
                                }
                                else
                                {
                                    if (productActionStatus == ProductActionStatus.SKUError)
                                    {
                                        num2++;
                                    }
                                    else
                                    {
                                        num2++;
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                    num2++;
                }
                i++;
            }
            System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(this.csvPath.Replace(".csv", ""));
            directoryInfo.Delete(true);
            System.IO.File.Delete(this.csvPath);
            System.IO.File.Delete(text);
            this.BindFiles();
            if (num2 == 0)
            {
                this.ShowMsg("此次商品批量导入操作已成功!", true);
                return;
            }
            this.ShowMsg("此次商品批量导入操作," + num2 + "件商品导入失败!", false);
        }
Esempio n. 42
0
 public bool HasAnimation(System.String name)
 {
     return(_animationList.ContainsKey(name));
 }
        /// <summary>
        /// 得到出货单dto
        /// </summary>
        /// <param name="bpObj"></param>
        /// <returns></returns>
        private System.Collections.Generic.List <UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData> GetShipDTOList(System.Collections.Generic.List <CarShipLineDTO> shiplist)
        {
            System.Collections.Generic.List <UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData> list = new System.Collections.Generic.List <UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData>();
            //string opeatorstr = "DMSTESTUSER";
            //string opeatorstr = "DMS";
            string opeatorstr = HBHCommon.DefaultShipOperatorCode;

            System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <CarShipLineDTO> > dic = new System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <CarShipLineDTO> >();
            foreach (CarShipLineDTO dtoline in shiplist)
            {
                if (!dic.ContainsKey(dtoline.SpitOrderFlag))
                {
                    dic.Add(dtoline.SpitOrderFlag, new System.Collections.Generic.List <CarShipLineDTO>());
                }
                dic[dtoline.SpitOrderFlag].Add(dtoline);
            }
            foreach (string key in dic.Keys)
            {
                List <CarShipLineDTO> listLineDTO = dic[key];

                if (listLineDTO != null &&
                    listLineDTO.Count > 0
                    )
                {
                    CarShipLineDTO firstDTO = listLineDTO.GetFirst <CarShipLineDTO>();

                    UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData shipdto = new UFIDA.U9.ISV.SM.ShipDTOForIndustryChainData();
                    shipdto.CreatedBy  = (Context.LoginUser);
                    shipdto.ModifiedBy = (Context.LoginUser);
                    string doctypecode = string.Empty;
                    shipdto.DocumentType = (new CommonArchiveDataDTOData());
                    if (firstDTO.OrderType == 401103 && firstDTO.IsSale)
                    {
                        doctypecode = "XM7";
                    }
                    else if (firstDTO.VehicleOrChassis == 400102)
                    {
                        doctypecode = "XM4";
                    }
                    else
                    {
                        doctypecode = "XM1";
                    }
                    shipdto.DocumentType.Code = (doctypecode);
                    long        ConfirmAccording = -1L;
                    int         ConfirmMode      = -1;
                    long        ConfirmTerm      = -1L;
                    long        InvoiceAccording = -1L;
                    long        ReceivableTerm   = -1L;
                    ShipDocType doctype          = ShipDocType.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), doctypecode), new OqlParam[0]);
                    if (doctype != null)
                    {
                        if (doctype.ConfirmAccordingKey != null)
                        {
                            ConfirmAccording = doctype.ConfirmAccordingKey.ID;
                        }
                        if (doctype.ConfirmMode.Value >= 0)
                        {
                            ConfirmMode = doctype.ConfirmMode.Value;
                        }
                        if (doctype.InvoiceAccordingKey != null)
                        {
                            InvoiceAccording = doctype.InvoiceAccordingKey.ID;
                        }
                    }
                    Customer customer = Customer.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), firstDTO.DealerCode), new OqlParam[0]);
                    if (customer != null)
                    {
                        if (customer.ARConfirmTermKey != null)
                        {
                            ConfirmTerm = customer.ARConfirmTermKey.ID;
                        }
                        if (customer.RecervalTermKey != null)
                        {
                            ReceivableTerm = customer.RecervalTermKey.ID;
                        }
                        shipdto.BargainMode  = (customer.Bargain.Value);
                        shipdto.ShipmentRule = (new CommonArchiveDataDTOData());
                        if (customer.ShippmentRule != null)
                        {
                            shipdto.ShipmentRule.Code = (customer.ShippmentRule.Code);
                        }
                        else
                        {
                            shipdto.ShipmentRule.Code = ("C001");
                        }
                        if (customer.RecervalTerm != null)
                        {
                            string RecTerm = customer.RecervalTerm.Code;
                        }
                    }
                    else
                    {
                        shipdto.ShipmentRule.Code = ("C001");
                        shipdto.BargainMode       = (0);
                    }
                    shipdto.SrcDocType     = (0);
                    shipdto.ReceivableTerm = (new CommonArchiveDataDTOData());
                    if (ReceivableTerm > 0L)
                    {
                        shipdto.ReceivableTerm.ID = (ReceivableTerm);
                    }
                    else
                    {
                        shipdto.ReceivableTerm.Code = ("01");
                    }
                    shipdto.ConfirmTerm = (new CommonArchiveDataDTOData());
                    if (ConfirmTerm > 0L)
                    {
                        shipdto.ConfirmTerm.ID = (ConfirmTerm);
                    }
                    else
                    {
                        shipdto.ConfirmTerm.Code = ("01");
                    }
                    shipdto.ConfirmAccording    = (new CommonArchiveDataDTOData());
                    shipdto.ConfirmAccording.ID = (ConfirmAccording);
                    shipdto.ConfirmMode         = ((ConfirmMode < 0) ? 0 : ConfirmMode);
                    shipdto.InvoiceAccording    = (new CommonArchiveDataDTOData());
                    shipdto.InvoiceAccording.ID = (InvoiceAccording);
                    shipdto.Seller      = (new CommonArchiveDataDTOData());
                    shipdto.Seller.Code = (opeatorstr);
                    Operators opeator = Operators.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), opeatorstr), new OqlParam[0]);
                    if (opeator != null)
                    {
                        shipdto.SaleDept    = (new CommonArchiveDataDTOData());
                        shipdto.SaleDept.ID = (opeator.DeptKey.ID);
                    }
                    shipdto.CreatedBy                     = (Context.LoginUser);
                    shipdto.CreatedOn                     = (System.DateTime.Now);
                    shipdto.OrderBy                       = (new CommonArchiveDataDTOData());
                    shipdto.OrderBy.Code                  = (firstDTO.DealerCode);
                    shipdto.AC                            = (new CommonArchiveDataDTOData());
                    shipdto.AC.Code                       = (string.IsNullOrEmpty(firstDTO.Currency) ? "C001" : firstDTO.Currency);
                    shipdto.TC                            = (new CommonArchiveDataDTOData());
                    shipdto.TC.Code                       = (string.IsNullOrEmpty(firstDTO.Currency) ? "C001" : firstDTO.Currency);
                    shipdto.DescFlexField                 = (new DescFlexSegmentsData());
                    shipdto.DescFlexField.PubDescSeg5     = (firstDTO.DmsSaleNo);
                    shipdto.DescFlexField.PrivateDescSeg1 = (firstDTO.DMSShipNo);
                    System.DateTime arg_5CD_0 = firstDTO.ShipDate;
                    if (firstDTO.ShipDate != System.DateTime.MinValue && firstDTO.ShipDate > System.DateTime.Now)
                    {
                        shipdto.BusinessDate = (firstDTO.ShipDate);
                    }
                    else
                    {
                        shipdto.BusinessDate = (System.DateTime.Now);
                    }
                    shipdto.ShipLines = (new System.Collections.Generic.List <UFIDA.U9.ISV.SM.ShipLineDTOForIndustryChainData>());
                    foreach (CarShipLineDTO linedto in listLineDTO)
                    {
                        UFIDA.U9.ISV.SM.ShipLineDTOForIndustryChainData shiplinedto = new UFIDA.U9.ISV.SM.ShipLineDTOForIndustryChainData();
                        shiplinedto.ItemInfo            = (new ItemInfoData());
                        shiplinedto.ItemInfo.ItemCode   = (linedto.ErpMaterialCode);
                        shiplinedto.ShipQtyTUAmount     = (linedto.Number);
                        shiplinedto.TotalMoneyTC        = (linedto.Money);
                        shiplinedto.TotalNetMoneyTC     = (linedto.Money);
                        shiplinedto.Project             = (new CommonArchiveDataDTOData());
                        shiplinedto.Project.Code        = (linedto.DmsSaleNo);
                        shiplinedto.ConfirmAccording    = (new CommonArchiveDataDTOData());
                        shiplinedto.ConfirmAccording.ID = (ConfirmAccording);
                        shiplinedto.ConfirmMode         = ((ConfirmMode < 0) ? 0 : ConfirmMode);
                        shiplinedto.ConfirmTerm         = (new CommonArchiveDataDTOData());
                        if (ConfirmTerm > 0L)
                        {
                            shiplinedto.ConfirmTerm.ID = (ConfirmTerm);
                        }
                        else
                        {
                            shiplinedto.ConfirmTerm.Code = ("01");
                        }
                        shiplinedto.InvoiceAccording    = (new CommonArchiveDataDTOData());
                        shiplinedto.InvoiceAccording.ID = (InvoiceAccording);
                        shiplinedto.ReceivableTerm      = (new CommonArchiveDataDTOData());
                        if (ReceivableTerm > 0L)
                        {
                            shiplinedto.ReceivableTerm.ID = (ReceivableTerm);
                        }
                        else
                        {
                            shiplinedto.ReceivableTerm.Code = ("01");
                        }
                        shiplinedto.WH = (new CommonArchiveDataDTOData());
                        string whcode = string.Empty;

                        /*  OrderType
                         * 401102;//预测订单
                         * 401101;//追加订单
                         * 401103;//监控车订单
                         * 401104;//储备订单
                         */
                        /*
                         * 0080	储运整车库
                         * 0081	储运车库2
                         * 0090	储运二类底盘库
                         */
                        /*
                         * 是不是 监控车订单,从 储运车库2 (0081) 发车;
                         * 底盘,从 储运二类底盘库 (0090) 发车;
                         * 其他订单,从  储运整车库 (0080) 发车?
                         */
                        if (firstDTO.OrderType == 401103 && firstDTO.IsSale)
                        {
                            whcode = "0081";
                        }
                        else if (firstDTO.VehicleOrChassis == 400102)
                        {
                            whcode = "0090";
                        }
                        else
                        {
                            whcode = "0080";
                        }
                        shiplinedto.WH.Code = (whcode);
                        Warehouse whout = Warehouse.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), whcode), new OqlParam[0]);
                        if (whout != null && whout.DepositType == DepositTypeEnum.VMI)
                        {
                            shiplinedto.VMI = (true);
                            //shiplinedto.VMI = whout.DepositType == DepositTypeEnum.VMI;
                            if (whout.Supplier != null)
                            {
                                shiplinedto.Supplier      = (new CommonArchiveDataDTOData());
                                shiplinedto.Supplier.Code = (whout.Supplier.Code);
                            }
                        }
                        shiplinedto.DescFlexField             = (new DescFlexSegmentsData());
                        shiplinedto.DescFlexField.PubDescSeg5 = (linedto.DmsSaleNo);
                        shiplinedto.Project      = (new CommonArchiveDataDTOData());
                        shiplinedto.Project.Code = (linedto.DmsSaleNo);
                        shiplinedto.DescFlexField.PubDescSeg13 = (linedto.EarnestMoney.ToString());
                        shiplinedto.DescFlexField.PubDescSeg14 = ((linedto.ShipMoney <= 0m) ? (linedto.Money - linedto.EarnestMoney).ToString() : linedto.ShipMoney.ToString());
                        shiplinedto.DescFlexField.PubDescSeg21 = (linedto.Deposit.ToString());
                        shiplinedto.DescFlexField.PubDescSeg12 = (linedto.VIN);
                        shipdto.ShipLines.Add(shiplinedto);
                    }
                    list.Add(shipdto);
                }
            }
            return(list);
        }
Esempio n. 44
0
 private static SQLCEVersion DetermineVersion(string filename)
 {
     var versionDictionary = new System.Collections.Generic.Dictionary<int, SQLCEVersion> 
 { 
     { 0x73616261, SQLCEVersion.SQLCE20 }, 
     { 0x002dd714, SQLCEVersion.SQLCE30},
     { 0x00357b9d, SQLCEVersion.SQLCE35},
     { 0x003d0900, SQLCEVersion.SQLCE40}
 };
     int versionLONGWORD = 0;
     try
     {
         using (var fs = new System.IO.FileStream(filename, System.IO.FileMode.Open))
         {
             fs.Seek(16, System.IO.SeekOrigin.Begin);
             using (System.IO.BinaryReader reader = new System.IO.BinaryReader(fs))
             {
                 versionLONGWORD = reader.ReadInt32();
             }
         }
     }
     catch
     {
         throw;
     }
     if (versionDictionary.ContainsKey(versionLONGWORD))
     {
         return versionDictionary[versionLONGWORD];
     }
     else
     {
         throw new ApplicationException("Unable to determine database file version");
     }
 }
Esempio n. 45
0
        private void lstBoxProducts_SelectedValueChanged(object sender, System.EventArgs e)
        {
            int product = (int)lstBoxProducts.SelectedIndex;

            switch (product)
            {
            case 0:
                txtProductInfo.Text =
                    @"MyGeneration is written in C# and is a tool that combines database meta-data with the power of scripting to generate stored procedures, data objects, business objects, user interfaces, and more.

Copyright © 2004-2006 by Mike Griffin and Justin Greenwood
All Rights Reserved";
                lnkURL.Text = @"http://www.mygenerationsoftware.com";
                break;

            case 1:
                txtProductInfo.Text =
                    @"MyMeta is C# COM object that serves up database meta-data with plug-in support.

Copyright © 2004-2006 by Mike Griffin and Justin Greenwood
All Rights Reserved";
                lnkURL.Text = @"http://www.mygenerationsoftware.com";
                break;

            case 2:
                txtProductInfo.Text =
                    @"The Zeus Parser contains the template parser and interpreter for MyGeneration.

Copyright © 2004-2006 by Mike Griffin and Justin Greenwood
All Rights Reserved";
                lnkURL.Text = @"http://www.mygenerationsoftware.com";
                break;

            case 3:
                txtProductInfo.Text =
                    @"The plug-in Interface contains interfaces allowing third parties to develop MyGeneration plug-ins.

Copyright © 2004-2005 by Mike Griffin and Justin Greenwood
All Rights Reserved";
                lnkURL.Text = @"http://www.mygenerationsoftware.com";
                break;

            case 4:

                txtProductInfo.Text =
                    @"ScintillaNET is an encapsulation of Scintilla for use within the .NET framework

The ScintillaNET bindings are Copyright © 2002-2003 by Garrett Serack";
                lnkURL.Text = @"http://sourceforge.net/projects/scide/";
                break;

            case 5:
                txtProductInfo.Text =
                    @"Scintilla is a free source code editing component. It comes with complete source code and a license that permits use in any free project or commercial product.

Copyright 1998-2002 by Neil Hodgson <*****@*****.**>
All Rights Reserved";
                lnkURL.Text = @"http://www.scintilla.org";
                break;

            case 6:
                txtProductInfo.Text =
                    @"DockPanel suite is designed to achieve docking capability for MDI forms. It can be used to develop applications with Visual Studio .Net style user interface. DockPanel suite is a 100%-native .Net windows forms control, written in C#.


Copyright © 2004 Weifen Luo, All Rights Reserved.";

                lnkURL.Text = @"http://sourceforge.net/projects/dockpanelsuite/";
                break;

            case 7:
                txtProductInfo.Text =
                    @"Npgsql is a .Net data provider for Postgresql. It allows any program developed for the .Net framework to access the Postgresql versions 7.x and 8.x. It is implemented in 100% C# code.

Copyright © 2002-2004  The Npgsql Development Team";


                lnkURL.Text = @"http://pgfoundry.org/projects/npgsql";
                break;

            case 8:
                txtProductInfo.Text =
                    @"The .NET Data provider/Driver is written in C# and provides a high-performance, native implementation of the Firebird API.";

                lnkURL.Text = @"http://www.firebirdsql.org/index.php?op=files&id=netprovider";
                break;

            case 9:
                txtProductInfo.Text =
                    @"System.Data.SQLite is an enhanced version of the original SQLite database engine. It is a complete drop-in replacement for the original sqlite3.dll (you can even rename it to sqlite3.dll).  It has no linker dependency on the .NET runtime so it can be distributed independently of .NET, yet embedded in the binary is a complete ADO.NET 2.0 provider for full managed development.

The C# provider, the very minor C code modifications to SQLite, documentation and etc were written by Robert Simpson.";
                lnkURL.Text = @"http://sqlite.phxsoftware.com/";
                break;

            case 10:
                txtProductInfo.Text =
                    @"VistaDB is a true RDBMS specifically designed for .NET to give developers a robust, high-speed embedded database solution with minimal overhead.

©1999-2004 Vista Software. All rights reserved.";

                lnkURL.Text = @"http://www.vistadb.net/";
                break;

            case 11:
                txtProductInfo.Text =
                    @"The DnpUtils plug-in for MyGeneration by David Parsons (dnparsons). This plug-in contains all kinds of useful functionality. See the Help menu for more details.";
                lnkURL.Text = @"http://www.mygenerationsoftware.com/TemplateLibrary/Archive/?guid=4a285a9a-4dd2-4655-b7ca-996b5516a5a1";
                break;

            default:
                if (plugins.ContainsKey(product))
                {
                    txtProductInfo.Text = this.plugins[product].ProviderAuthorInfo;
                    if (this.plugins[product].ProviderAuthorUri != null)
                    {
                        lnkURL.Text = plugins[product].ProviderAuthorUri.ToString();
                    }
                    else
                    {
                        lnkURL.Text = "http://www.mygenerationsoftware.com/";
                    }
                }
                break;
            }
        }
Esempio n. 46
0
        // public static void  encode(System.String content, ErrorCorrectionLevel ecLevel, System.Collections.Hashtable hints, QRCode qrCode) // commented by .net follower (http://dotnetfollower.com)
        public static void encode(System.String content, ErrorCorrectionLevel ecLevel, System.Collections.Generic.Dictionary <Object, Object> hints, QRCode qrCode) // added by .net follower (http://dotnetfollower.com)
        {
            // System.String encoding = hints == null?null:(System.String) hints[EncodeHintType.CHARACTER_SET]; // commented by .net follower (http://dotnetfollower.com)
            System.String encoding = null;                                        // added by .net follower (http://dotnetfollower.com)
            if (hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET)) // added by .net follower (http://dotnetfollower.com)
            {
                encoding = (System.String)hints[EncodeHintType.CHARACTER_SET];    // added by .net follower (http://dotnetfollower.com)
            }
            if (encoding == null)
            {
                encoding = DEFAULT_BYTE_MODE_ENCODING;
            }

            // Step 1: Choose the mode (encoding).
            Mode mode = chooseMode(content, encoding);

            // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
            BitVector dataBits = new BitVector();

            appendBytes(content, mode, dataBits, encoding);
            // Step 3: Initialize QR code that can contain "dataBits".
            int numInputBytes = dataBits.sizeInBytes();

            initQRCode(numInputBytes, ecLevel, mode, qrCode);

            // Step 4: Build another bit vector that contains header and data.
            BitVector headerAndDataBits = new BitVector();

            // Step 4.5: Append ECI message if applicable
            if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding))
            {
                CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
                if (eci != null)
                {
                    appendECI(eci, headerAndDataBits);
                }
            }

            appendModeInfo(mode, headerAndDataBits);

            int numLetters = mode.Equals(Mode.BYTE)?dataBits.sizeInBytes():content.Length;

            appendLengthInfo(numLetters, qrCode.Version, mode, headerAndDataBits);
            headerAndDataBits.appendBitVector(dataBits);

            // Step 5: Terminate the bits properly.
            terminateBits(qrCode.NumDataBytes, headerAndDataBits);

            // Step 6: Interleave data bits with error correction code.
            BitVector finalBits = new BitVector();

            interleaveWithECBytes(headerAndDataBits, qrCode.NumTotalBytes, qrCode.NumDataBytes, qrCode.NumRSBlocks, finalBits);

            // Step 7: Choose the mask pattern and set to "qrCode".
            ByteMatrix matrix = new ByteMatrix(qrCode.MatrixWidth, qrCode.MatrixWidth);

            qrCode.MaskPattern = chooseMaskPattern(finalBits, qrCode.ECLevel, qrCode.Version, matrix);

            // Step 8.  Build the matrix and set it to "qrCode".
            MatrixUtil.buildMatrix(finalBits, qrCode.ECLevel, qrCode.Version, qrCode.MaskPattern, matrix);
            qrCode.Matrix = matrix;
            // Step 9.  Make sure we have a valid QR Code.
            if (!qrCode.Valid)
            {
                throw new WriterException("Invalid QR code: " + qrCode.ToString());
            }
        }
Esempio n. 47
0
        /// <summary> <p>Detects a Data Matrix Code in an image.</p>
        ///
        /// </summary>
        /// <returns> {@link DetectorResult} encapsulating results of detecting a QR Code
        /// </returns>
        /// <throws>  ReaderException if no Data Matrix Code can be found </throws>
        public DetectorResult detect()
        {
            ResultPoint[] cornerPoints = rectangleDetector.detect();
            ResultPoint   pointA       = cornerPoints[0];
            ResultPoint   pointB       = cornerPoints[1];
            ResultPoint   pointC       = cornerPoints[2];
            ResultPoint   pointD       = cornerPoints[3];

            // Point A and D are across the diagonal from one another,
            // as are B and C. Figure out which are the solid black lines
            // by counting transitions
            System.Collections.Generic.List <Object> transitions = new System.Collections.Generic.List <Object>(4); //GregBray: Removed Synchronized wrapper
            transitions.Add(transitionsBetween(pointA, pointB));
            transitions.Add(transitionsBetween(pointA, pointC));
            transitions.Add(transitionsBetween(pointB, pointD));
            transitions.Add(transitionsBetween(pointC, pointD));
            Collections.insertionSort(transitions, new ResultPointsAndTransitionsComparator());

            // Sort by number of transitions. First two will be the two solid sides; last two
            // will be the two alternating black/white sides
            ResultPointsAndTransitions lSideOne = (ResultPointsAndTransitions)transitions[0];
            ResultPointsAndTransitions lSideTwo = (ResultPointsAndTransitions)transitions[1];

            // Figure out which point is their intersection by tallying up the number of times we see the
            // endpoints in the four endpoints. One will show up twice.
            System.Collections.Generic.Dictionary <Object, Object> pointCount = new System.Collections.Generic.Dictionary <Object, Object>();
            increment(pointCount, lSideOne.From);
            increment(pointCount, lSideOne.To);
            increment(pointCount, lSideTwo.From);
            increment(pointCount, lSideTwo.To);

            ResultPoint maybeTopLeft     = null;
            ResultPoint bottomLeft       = null;
            ResultPoint maybeBottomRight = null;

            System.Collections.IEnumerator points = pointCount.Keys.GetEnumerator();
            //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
            while (points.MoveNext())
            {
                //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
                ResultPoint  point         = (ResultPoint)points.Current;
                System.Int32 value_Renamed = (System.Int32)pointCount[point];
                if (value_Renamed == 2)
                {
                    bottomLeft = point;                     // this is definitely the bottom left, then -- end of two L sides
                }
                else
                {
                    // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now
                    if (maybeTopLeft == null)
                    {
                        maybeTopLeft = point;
                    }
                    else
                    {
                        maybeBottomRight = point;
                    }
                }
            }

            if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null)
            {
                throw ReaderException.Instance;
            }

            // Bottom left is correct but top left and bottom right might be switched
            ResultPoint[] corners = new ResultPoint[] { maybeTopLeft, bottomLeft, maybeBottomRight };
            // Use the dot product trick to sort them out
            ResultPoint.orderBestPatterns(corners);

            // Now we know which is which:
            ResultPoint bottomRight = corners[0];

            bottomLeft = corners[1];
            ResultPoint topLeft = corners[2];

            // Which point didn't we find in relation to the "L" sides? that's the top right corner
            ResultPoint topRight;

            if (!pointCount.ContainsKey(pointA))
            {
                topRight = pointA;
            }
            else if (!pointCount.ContainsKey(pointB))
            {
                topRight = pointB;
            }
            else if (!pointCount.ContainsKey(pointC))
            {
                topRight = pointC;
            }
            else
            {
                topRight = pointD;
            }

            // Next determine the dimension by tracing along the top or right side and counting black/white
            // transitions. Since we start inside a black module, we should see a number of transitions
            // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to
            // end on a black module:

            // The top right point is actually the corner of a module, which is one of the two black modules
            // adjacent to the white module at the top right. Tracing to that corner from either the top left
            // or bottom right should work here. The number of transitions could be higher than it should be
            // due to noise. So we try both and take the min.

            int dimension = System.Math.Min(transitionsBetween(topLeft, topRight).Transitions, transitionsBetween(bottomRight, topRight).Transitions);

            if ((dimension & 0x01) == 1)
            {
                // it can't be odd, so, round... up?
                dimension++;
            }
            dimension += 2;

            BitMatrix bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, dimension);

            return(new DetectorResult(bits, new ResultPoint[] { pointA, pointB, pointC, pointD }));
        }
Esempio n. 48
0
        public System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>> ReadAllData(int titleLine)
        {
            System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>> csvReaderData = new System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>>();
            System.Collections.Generic.List<string[]> csvReaderRow = this.ReadAllRow();
            string[] titles = csvReaderRow[titleLine];
            for (int i = titleLine + 1; i < csvReaderRow.Count; i++)
            {

                System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();
                for (int ii = 0; ii < titles.Length; ii++)
                {

                    try
                    {
                        if (dic.ContainsKey(titles[ii].Trim()))
                        {
                            for (int k = 0; k < 1000; k++)
                            {
                                if (!dic.ContainsKey(titles[ii].Trim() + k))
                                {
                                    dic.Add(titles[ii].Trim() + k, csvReaderRow[i][ii]);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (csvReaderRow[i].Length > ii)
                            {
                                dic.Add(titles[ii].Trim(), csvReaderRow[i][ii]);
                            }
                        }
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
                csvReaderData.Add(dic);
            }
            return csvReaderData;
        }
Esempio n. 49
0
 public override bool Contains(string path, uint group_tag)
 {
     return(lookup.ContainsKey(new Entry(path, group_tag)));
 }
Esempio n. 50
0
        public virtual void SetObjects(uint count, object[] punk)
        {
            if (punk == null)
            {
                return;
            }

            if(count > 0)
            {
                if(punk[0] is ProjectConfig)
                {
                    ArrayList configs = new ArrayList();

                    for(int i = 0; i < count; i++)
                    {
                        ProjectConfig config = (ProjectConfig)punk[i];

                        if(this.project == null)
                        {
                            this.project = config.ProjectMgr;
                        }

                        configs.Add(config);
                    }

                    this.projectConfigs = (ProjectConfig[])configs.ToArray(typeof(ProjectConfig));
                }
                else if(punk[0] is NodeProperties)
                {
                    if(this.project == null)
                    {
                        this.project = (punk[0] as NodeProperties).Node.ProjectMgr;
                    }

                    System.Collections.Generic.Dictionary<string, ProjectConfig> configsMap = new System.Collections.Generic.Dictionary<string, ProjectConfig>();

                    for(int i = 0; i < count; i++)
                    {
                        NodeProperties property = (NodeProperties)punk[i];
                        IVsCfgProvider provider;
                        ErrorHandler.ThrowOnFailure(property.Node.ProjectMgr.GetCfgProvider(out provider));
                        uint[] expected = new uint[1];
                        ErrorHandler.ThrowOnFailure(provider.GetCfgs(0, null, expected, null));
                        if(expected[0] > 0)
                        {
                            ProjectConfig[] configs = new ProjectConfig[expected[0]];
                            uint[] actual = new uint[1];
                            ErrorHandler.ThrowOnFailure(provider.GetCfgs(expected[0], configs, actual, null));

                            foreach(ProjectConfig config in configs)
                            {
                                if(!configsMap.ContainsKey(config.ConfigName))
                                {
                                    configsMap.Add(config.ConfigName, config);
                                }
                            }
                        }
                    }

                    if(configsMap.Count > 0)
                    {
                        if(this.projectConfigs == null)
                        {
                            this.projectConfigs = new ProjectConfig[configsMap.Keys.Count];
                        }
                        configsMap.Values.CopyTo(this.projectConfigs, 0);
                    }
                }
            }
            else
            {
                this.project = null;
            }

            if(this.active && this.project != null)
            {
                UpdateObjects();
            }
        }
Esempio n. 51
0
		private void  NoDupDirs(Directory[] dirs)
		{
            System.Collections.Generic.Dictionary<Directory, Directory> dups = new System.Collections.Generic.Dictionary<Directory, Directory>();
			for (int i = 0; i < dirs.Length; i++)
			{
                if (dups.ContainsKey(dirs[i]))
				{
					throw new System.ArgumentException("Directory " + dirs[i] + " appears more than once");
				}
				if (dirs[i] == directory)
					throw new System.ArgumentException("Cannot add directory to itself");
                dups[dirs[i]] = dirs[i];
            }
		}
Esempio n. 52
0
        Bam.Core.IBuilderPostExecute.PostExecute(
            Bam.Core.DependencyNodeCollection executedNodes)
        {
            Bam.Core.Log.DebugMessage("PostExecute for QMakeBuilder");

            if (0 == executedNodes.Count)
            {
                Bam.Core.Log.Info("No QMake pro file written as there were no targets generated");
                return;
            }

            // find all nodes with the same unique name
            var similarNodes = new System.Collections.Generic.Dictionary <string, Bam.Core.Array <QMakeData> >();

            foreach (var node in executedNodes)
            {
                if (null == node.Data)
                {
                    Bam.Core.Log.DebugMessage("*** Null data for node {0}", node.UniqueModuleName);
                    continue;
                }

                if (similarNodes.ContainsKey(node.UniqueModuleName))
                {
                    similarNodes[node.UniqueModuleName].Add(node.Data as QMakeData);
                }
                else
                {
                    similarNodes[node.UniqueModuleName] = new Bam.Core.Array <QMakeData>(node.Data as QMakeData);
                }
            }

            foreach (var keyPair in similarNodes)
            {
                Bam.Core.Log.DebugMessage("{0} : {1} nodes", keyPair.Key, keyPair.Value.Count);
                QMakeData.Write(keyPair.Value);
            }

#if false
            var mainPackage   = Bam.Core.State.PackageInfo[0];
            var proFileName   = mainPackage + ".pro";
            var rootDirectory = Bam.Core.State.BuildRoot;
            var proFilePath   = System.IO.Path.Combine(rootDirectory, proFileName);

            // relative paths need a trailing slash to work
            rootDirectory += System.IO.Path.DirectorySeparatorChar;

            using (var proWriter = new System.IO.StreamWriter(proFilePath))
            {
                proWriter.WriteLine("# -- Generated by BuildAMation --");
                proWriter.WriteLine("TEMPLATE = subdirs");
                proWriter.WriteLine("CONFIG += ordered");
                proWriter.WriteLine("SUBDIRS += \\");

                foreach (var collection in similarNodes.Values)
                {
                    var data = collection[0];
                    if (data.ProFilePath != null)
                    {
                        var subDirProjectDir = System.IO.Path.GetDirectoryName(data.ProFilePath) + System.IO.Path.DirectorySeparatorChar;
                        var relativeDir      = Bam.Core.RelativePathUtilities.GetPath(subDirProjectDir, rootDirectory);
                        relativeDir = relativeDir.TrimEnd(System.IO.Path.DirectorySeparatorChar);
                        proWriter.WriteLine("\t{0}\\", relativeDir.Replace('\\', '/'));
                    }
                }
            }

            Bam.Core.Log.Info("Successfully created QMake .pro file for package '{0}'\n\t{1}", Bam.Core.State.PackageInfo[0].Name, proFilePath);
#endif
        }
        // 得到调入单dto
        /// <summary>
        /// 得到调入单dto
        /// </summary>
        /// <param name="bpObj"></param>
        /// <returns></returns>
        private System.Collections.Generic.List<ISV.TransferInISV.IC_TransferInDTOData> GetTransferInDTOList(CreateApprovedTransferInSV bpObj)
        {
            System.Collections.Generic.List<ISV.TransferInISV.IC_TransferInDTOData> list = new System.Collections.Generic.List<ISV.TransferInISV.IC_TransferInDTOData>();
            System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<TransInLineDTO>> dic = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<TransInLineDTO>>();
            foreach (TransInLineDTO dtoline in bpObj.TransferInLineDTOList)
            {
                if (!dic.ContainsKey(dtoline.SpitOrderFlag))
                {
                    dic.Add(dtoline.SpitOrderFlag, new System.Collections.Generic.List<TransInLineDTO>());
                }
                dic[dtoline.SpitOrderFlag].Add(dtoline);
            }
            foreach (string key in dic.Keys)
            {
                List<TransInLineDTO> listLineDTO = dic[key];

                if (listLineDTO != null
                    && listLineDTO.Count > 0
                    )
                {
                    TransInLineDTO firstDTO = listLineDTO.GetFirst<TransInLineDTO>();

                    ISV.TransferInISV.IC_TransferInDTOData transindto = new ISV.TransferInISV.IC_TransferInDTOData();
                    transindto.TransInDocType = (new CommonArchiveDataDTOData());
                    if (firstDTO.OperationType == 1)
                    {
                        transindto.TransInDocType.Code = ("MoveWH");
                    }
                    else if (firstDTO.OperationType == 2)
                    {
                        transindto.TransInDocType.Code = ("CarOutWH");
                    }
                    transindto.CreatedBy = (Context.LoginUser);
                    transindto.CreatedOn = (System.DateTime.Now);
                    transindto.ModifiedBy = (Context.LoginUser);
                    transindto.ModifiedOn = (System.DateTime.Now);
                    transindto.DescFlexField = (new DescFlexSegmentsData());
                    transindto.DescFlexField.PrivateDescSeg4 = (firstDTO.TransDocNo);
                    transindto.TransInLines = (new System.Collections.Generic.List<ISV.TransferInISV.IC_TransInLineDTOData>());
                    foreach (TransInLineDTO linedto in listLineDTO)
                    {
                        ISV.TransferInISV.IC_TransInLineDTOData transinlinedto = new ISV.TransferInISV.IC_TransInLineDTOData();
                        transinlinedto.ItemInfo = (new ItemInfoData());
                        transinlinedto.ItemInfo.ItemCode = (linedto.ItemMaster);
                        transinlinedto.TransInWh = (new CommonArchiveDataDTOData());
                        transinlinedto.TransInWh.Code = (linedto.WhIn);
                        Warehouse whin = Warehouse.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), linedto.WhIn), new OqlParam[0]);
                        if (whin != null)
                        {
                            transinlinedto.StorageType = (whin.StorageType.Value);
                        }
                        else
                        {
                            transinlinedto.StorageType = (4);
                        }
                        transinlinedto.StoreUOMQty = (linedto.Number);
                        transinlinedto.CostCurrency = (new CommonArchiveDataDTOData());
                        transinlinedto.CostCurrency.Code = (linedto.Currency);
                        transinlinedto.DescFlexSegments = (new DescFlexSegmentsData());
                        transinlinedto.DescFlexSegments.PubDescSeg12 = (linedto.VIN);
                        transinlinedto.Project = (new CommonArchiveDataDTOData());
                        transinlinedto.Project.Code = (linedto.TransDocNo);
                        transinlinedto.TransInSubLines = (new System.Collections.Generic.List<ISV.TransferInISV.IC_TransInSubLineDTOData>());
                        ISV.TransferInISV.IC_TransInSubLineDTOData sublinedto = new ISV.TransferInISV.IC_TransInSubLineDTOData();
                        sublinedto.TransOutWh = (new CommonArchiveDataDTOData());
                        sublinedto.TransOutWh.Code = (linedto.WhOut);
                        sublinedto.Project = (new CommonArchiveDataDTOData());
                        sublinedto.Project.Code = (linedto.TransDocNo);
                        Warehouse whout = Warehouse.Finder.Find(string.Format("Org={0} and Code='{1}'", Context.LoginOrg.ID.ToString(), linedto.WhOut), new OqlParam[0]);
                        if (whout != null)
                        {
                            sublinedto.StorageType = (whout.StorageType.Value);
                        }
                        else
                        {
                            sublinedto.StorageType = (4);
                        }
                        transinlinedto.TransInSubLines.Add(sublinedto);
                        transindto.TransInLines.Add(transinlinedto);
                    }
                    list.Add(transindto);
                }
            }
            return list;
        }
Esempio n. 54
0
        public override void OnWindowActivated(Window GotFocus, Window LostFocus)
        {
            try
            {
                if (GotFocus == null)
                {
                    return;
                }
                IDesignerHost designer = GotFocus.Object as IDesignerHost;
                if (designer == null)
                {
                    return;
                }
                ProjectItem pi = GotFocus.ProjectItem;
                if ((pi == null) || (!(pi.Object is Cube)))
                {
                    return;
                }
                EditorWindow   win     = (EditorWindow)designer.GetService(typeof(Microsoft.DataWarehouse.ComponentModel.IComponentNavigator));
                VsStyleToolBar toolbar = (VsStyleToolBar)win.SelectedView.GetType().InvokeMember("ToolBar", getflags, null, win.SelectedView, null);

                IntPtr ptr     = win.Handle;
                string sHandle = ptr.ToInt64().ToString();

                if (!windowHandlesFixedForCalcProperties.ContainsKey(sHandle))
                {
                    windowHandlesFixedForCalcProperties.Add(sHandle, win);
                    win.ActiveViewChanged += new EventHandler(win_ActiveViewChanged);
                }

                if (win.SelectedView.MenuItemCommandID.ID == 12899)
                //if (win.SelectedView.Caption == "Calculations")
                {
                    int  iMicrosoftCalcPropertiesIndex = 0;
                    bool bFlipScriptViewButton         = false;
                    foreach (ToolBarButton b in toolbar.Buttons)
                    {
                        Microsoft.DataWarehouse.Controls.MenuCommandToolBarButton tbb = b as Microsoft.DataWarehouse.Controls.MenuCommandToolBarButton;
                        if (tbb != null && tbb.AssociatedCommandID.ID == (int)BIDSToolbarButtonID.CalculationProperties)
                        //if (b.ToolTipText.StartsWith("Calculation Properties"))
                        {
                            if (b.Tag == null || b.Tag.ToString() != this.FullName + ".CommandProperties")
                            {
                                if (!toolbar.Buttons.ContainsKey(this.FullName + ".CommandProperties"))
                                {
                                    //if we haven't created it yet
                                    iMicrosoftCalcPropertiesIndex = toolbar.Buttons.IndexOf(b);
                                    b.Visible = false;

                                    newCalcPropButton             = new ToolBarButton();
                                    newCalcPropButton.ToolTipText = "Calculation Properties (BIDS Helper)";
                                    newCalcPropButton.Name        = this.FullName + ".CommandProperties";
                                    newCalcPropButton.Tag         = newCalcPropButton.Name;
#if KATMAI || DENALI || SQL2014
                                    newCalcPropButton.ImageIndex = 12;
#else
                                    newCalcPropButton.ImageIndex = 11;
#endif
                                    newCalcPropButton.Enabled = true;
                                    newCalcPropButton.Style   = ToolBarButtonStyle.PushButton;

                                    toolbar.ImageList.Images.Add(BIDSHelper.Resources.Common.DeployMdxScriptIcon);

                                    if (pi.Name.ToLower().EndsWith(".cube")) //only show feature if we're in offline mode
                                    {
                                        // TODO - does not disable if Deploy plugin is disabled after the button has been added
                                        if (Connect.Plugins[DeployMDXScriptPlugin.BaseName + typeof(DeployMDXScriptPlugin).Name].Enabled)
                                        {
                                            newDeployMdxScriptButton             = new ToolBarButton();
                                            newDeployMdxScriptButton.ToolTipText = "Deploy MDX Script (BIDS Helper)";
                                            newDeployMdxScriptButton.Name        = this.FullName + ".DeployMdxScript";
                                            newDeployMdxScriptButton.Tag         = newDeployMdxScriptButton.Name;
                                            newDeployMdxScriptButton.ImageIndex  = toolbar.ImageList.Images.Count - 1;
                                            newDeployMdxScriptButton.Enabled     = true;
                                            newDeployMdxScriptButton.Style       = ToolBarButtonStyle.PushButton;
                                        }
                                    }

                                    //catch the button clicks of the new buttons we just added
                                    toolbar.ButtonClick += new ToolBarButtonClickEventHandler(toolbar_ButtonClick);

                                    //catch the mouse clicks... the only way to catch the button click for the Microsoft buttons
                                    toolbar.Click += new EventHandler(toolbar_Click);
                                }
                            }
                        }
                        else if (tbb != null && tbb.AssociatedCommandID.ID == 12854 && ScriptViewDefault && !windowHandlesFixedDefaultCalcScriptView.ContainsKey(sHandle))
                        //else if (b.ToolTipText == "Form View" && ScriptViewDefault && !windowHandlesFixedDefaultCalcScriptView.ContainsKey(sHandle)) //12854
                        {
                            Control control = (Control)win.SelectedView.GetType().InvokeMember("ViewControl", getflags, null, win.SelectedView, null);
                            System.Reflection.BindingFlags getfieldflags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                            object controlMgr = control.GetType().InvokeMember("calcControlMgr", getfieldflags, null, control, null);
                            System.Reflection.BindingFlags getmethodflags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                            controlMgr.GetType().InvokeMember("ViewScript", getmethodflags, null, controlMgr, new object[] { });
                            bFlipScriptViewButton = true;
                            b.Pushed = false;
                            windowHandlesFixedDefaultCalcScriptView.Add(sHandle, win);
                        }
                        else if (tbb != null && tbb.AssociatedCommandID.ID == (int)BIDSHelper.BIDSToolbarButtonID.ScriptView && bFlipScriptViewButton)  //12853
                        //else if (b.ToolTipText == "Script View" && bFlipScriptViewButton) //12853
                        {
                            b.Pushed = true;
                        }
                    }
                    if (newDeployMdxScriptButton != null && !toolbar.Buttons.Contains(newDeployMdxScriptButton))
                    {
                        toolbar.Buttons.Insert(iMicrosoftCalcPropertiesIndex, newDeployMdxScriptButton);
                    }
                    if (newCalcPropButton != null && !toolbar.Buttons.Contains(newCalcPropButton))
                    {
                        toolbar.Buttons.Insert(iMicrosoftCalcPropertiesIndex, newCalcPropButton);
                    }
                }
            }
            catch { }
        }
Esempio n. 55
0
    public void setHourlyRecord(Worksheet targetSheet, Models.Student student)
    {
        var collector = new System.Collections.Generic.Dictionary<ExcelExport.Key, int>();
        foreach (var b in student.Behaviors)
        {
            var key = new ExcelExport.Key { DayOfWeek = b.TimeRecorded.DayOfWeek.ToString(), Hour = b.TimeRecorded.Hour };
            if (collector.ContainsKey(key))
                collector[key] += 1;
            else
                collector.Add(key, 1);

        }
        foreach (var key in collector.Keys)
        {
            var value = key.Hour - 1;
                switch (key.DayOfWeek.ToString())
                {
                    case "Monday": ((Range)(targetSheet.Cells[6, value])).Value = collector[key];
                        break;
                    case "Tuesday": ((Range)(targetSheet.Cells[7, value])).Value = collector[key];
                        break;
                    case "Wednesday": ((Range)(targetSheet.Cells[8, value])).Value = collector[key];
                        break;
                    case "Thursday": ((Range)(targetSheet.Cells[9, value])).Value = collector[key];
                        break;
                    case "Friday": ((Range)(targetSheet.Cells[10, value])).Value = collector[key];
                        break;
                    default:
                        break;
                }
            }
    }
    private IEnumerator GetAndSendMedPollData()
    {
        //Orbit data
        System.Collections.Generic.Dictionary<string, double> DoubleValues = new System.Collections.Generic.Dictionary<string, double>();
        DoubleValues["o.ApA"] = this.vessel.orbit.ApA;
        DoubleValues["o.PeA"] = this.vessel.orbit.PeA;
        DoubleValues["o.timeToAp"] = this.vessel.orbit.timeToAp;
        DoubleValues["o.timeToPe"] = this.vessel.orbit.timeToPe;
        DoubleValues["o.inclination"] = this.vessel.orbit.inclination;
        DoubleValues["o.eccentricity"] = this.vessel.orbit.eccentricity;
        //Resource data
        System.Collections.Generic.Dictionary<string, double> ResourceCurrent = new System.Collections.Generic.Dictionary<string, double>();
        System.Collections.Generic.Dictionary<string, double> ResourceMax = new System.Collections.Generic.Dictionary<string, double>();

        DoubleValues ["v.overheatRatio"] = 0.0d;

        foreach (Part part in this.vessel.parts) {
            //resources
            if (part.Resources.Count > 0) {
                foreach (PartResource partResource in part.Resources) {
                    if (!ResourceCurrent.ContainsKey(partResource.resourceName)) { ResourceCurrent [partResource.resourceName] = 0; }
                    if (!ResourceMax.ContainsKey(partResource.resourceName))     { ResourceMax     [partResource.resourceName] = 0; }
                    ResourceCurrent [partResource.resourceName] += partResource.amount;
                    ResourceMax     [partResource.resourceName] += partResource.maxAmount;
                }
            }
            //overheat
            foreach (PartModule pm in part.Modules) {
                if (!pm.isEnabled) { continue; }
                var thatEngineModule = pm as ModuleEngines;
                var thatEngineModuleFX = pm as ModuleEnginesFX;
                if (thatEngineModule != null || thatEngineModuleFX != null) {
                    double thistempratio = part.temperature / part.maxTemp;
                    DoubleValues ["v.overheatRatio"] = (thistempratio > DoubleValues ["v.overheatRatio"]) ? thistempratio : DoubleValues ["v.overheatRatio"];
                }
            }
        }
        DoubleValues ["v.overheat"] = 0.0;
        foreach (Part thatPart in this.vessel.parts) {

        }
        //POST DATA
        var form = new WWWForm();
        form.AddField("type", "med");
        form.AddField("time", UnixTimeAsString());
        foreach (System.Collections.Generic.KeyValuePair<string, double> entry in DoubleValues)
        {
            form.AddField(entry.Key,entry.Value.ToString());
        }
        foreach (System.Collections.Generic.KeyValuePair<string, double> entry in ResourceCurrent)
        {
            form.AddField("r.resource["+entry.Key+"]", ResourceCurrent[entry.Key].ToString());
        }
        foreach (System.Collections.Generic.KeyValuePair<string, double> entry in ResourceMax)
        {
            form.AddField("r.resourceMax["+entry.Key+"]", ResourceMax[entry.Key].ToString());
        }
        var post = new WWW(postlocation,form);
        yield return post;
        if (!string.IsNullOrEmpty(post.error))
            print("GetAndSendMedPollData: WWWFORM ERROR:" + post.error);
        else
            print("GetAndSendMedPollData: WWWFORM: Finished Uploading Data");
        next_med_poll_time = Time.time + med_freq;
    }
Esempio n. 57
0
        public Event(DateTime ClockStart, DateTime ClockEnd, int ClockRunTime, System.Xml.Linq.XDocument XMLEvents, ref CrashHandler Crash)
        {
            ch = Crash;
            events = new Dictionary<string, List<EventItem>>();
            clock = new PartyClock(ClockStart, ClockEnd, ClockRunTime);
            Util.ShowClock = true;
            sound = new Sound(true);
            text = new Text2D();
            chess = new Chess();
            sf = new Starfield(150);

            intro = new Intro(ref sound, ref text);
            outro = new Outro(ref sound);

            advent = new Advent(ref sound);
            birthday = new Birthday(ref sound, ref text, ref chess);
            xmas = new Christmas(ref sound);
            smurf = new Datasmurf(ref sound, ref text); // random
            dif = new Dif(ref chess, ref sound); // random
            fbk = new Fbk(ref sound); // random
            hw = new Halloween(ref chess, ref sound, 25);
            lucia = new Lucia(ref chess, ref sound);
            newyear = new NewYear();
            richard = new RMS(ref sound, ref text); // random
            scroller = new Scroller(ref chess, ref sf, ref text); // random
            semla = new Semla();
            sune = new SuneAnimation(ref sound, ref text);
            tl = new TurboLogo(ref sound, ref chess, (OpenGL.Util.SpringOrFall.Equals("Spring")? true:false)/*((ClockStart.Month >= 1 && ClockStart.Month <= 8)? false:true)*/ ); // vilken termin är det? jan till början av augusti VT, resten HT... random
            valentine = new Valentine(ref sound);
            wl = new WinLinux(ref chess); //random
            creators = new Self(ref sound); // random
            bb = new BB(ref sound); // random
            GM = new GummiBears(ref sound);
            NDay = new National(ref chess, ref sound);
            easter = new Easter(ref sound);
            hajk = new Hajk(ref sound);
            mid = new Midsummer(ref sound);
            vaf = new Vaffla();
            wp = new Walpurgis();
            crayfish = new CrayFish();

            ts = new TeknatStyle(ref chess, ref sound, ref text);
            m = new Matrix(ref text);
            q = new Quiz(ref text, false, ref sound);
            talepsin = new Talespin(ref sound);
            cd = new ChipAndDale(ref sound, ref chess);
            nerd = new Nerdy(ref chess, ref sound);
            trex = new Trex(ref sound);
            sailormoon = new Sailormoon(ref sound,ref chess);
            gb = new GhostBusters(ref sound);
            zelda = new Zelda(ref sound, ref chess);
            tardis = new Tardis(ref sound);
            f**k = new F**k(ref sound, ref chess);

            silverFang = new SilverFang(ref sound);
            mt = new MoraT(ref sound);

            swine = new Swine(ref chess, ref text);
            tjall = new Tjall(ref chess, ref text);

            ronja = new Ronja(ref sound);
            emil = new Emil(ref sound);
            djungelboken = new Djungelboken(ref sound);
            fabbe = new Fabbe(ref sound);
            drink = new Drink(ref sound);
            frozen = new Frozen(ref sound);

            eventCurrent = null; // event item for events to be triggerd in clock_NewDate
            //randomEvent = new List<string>(new string[] { "starfield", "SuneAnimation", "TurboLogo", "Datasmurf", "WinLinux", "Scroller", "BB", "GummiBears", "TeknatStyle", "Matrix"});
            randomEvent = new List<string>(new string[] { "starfield", "Nerdy", "Talespin", "Sailormoon", "GhostBusters", "Zelda", "Tardis", "F**k", "SilverFang", "MoraT" });
            //new stuff
             List<UtilXML.EventData> ed = UtilXML.Loadeffectdata();

            // TODO: Make a clean list with all events allowed to be used implement so that it is actaully usable instead of a switch at the bottom of this file.
            Dictionary<string, Effect> effects = new Dictionary<string, Effect>()
            {
                {"SuneAnimation", new Effect(sune, ed.Find(e => e.Name == "SuneAnimation"))},
                {"Dif",new Effect(dif, ed.Find(e => e.Name == "Dif"))},
                {"Fbk",new Effect(fbk, ed.Find(e => e.Name == "Fbk"))},
                {"TurboLogo",new Effect(tl, ed.Find(e => e.Name == "TurboLogo"))},
                {"Datasmurf", new Effect(smurf, ed.Find(e => e.Name == "Datasmurf"))},
                {"RMS",new Effect(richard, ed.Find(e => e.Name == "RMS"))},
                {"WinLinux",new Effect(wl, ed.Find(e => e.Name == "WinLinux"))},
                {"Scroller",new Effect(scroller, ed.Find(e => e.Name == "Scroller"))},
                {"Self",new Effect(creators, ed.Find(e => e.Name == "Self"))},
                {"BB",new Effect(bb, ed.Find(e => e.Name == "BB"))},
                {"GummiBears",new Effect(GM, ed.Find(e => e.Name == "GummiBears"))},
                {"Hajk",new Effect(hajk, ed.Find(e => e.Name == "Hajk"))},
                {"TeknatStyle",new Effect(ts, ed.Find(e => e.Name == "TeknatStyle"))},
                {"Matrix",new Effect(m, ed.Find(e => e.Name == "Matrix"))},
                {"Quiz",new Effect(q, ed.Find(e => e.Name == "Quiz"))},
                {"Talespin",new Effect(talepsin, ed.Find(e => e.Name == "Talespin"))},
                {"ChipDale",new Effect(cd, ed.Find(e => e.Name == "ChipDale"))},
                {"Nerdy",new Effect(nerd, ed.Find(e => e.Name == "Nerdy"))},
              /*  {"Trex",new Effect(trex, ed.Find(e => e.Name == "Trex"))},*/
                {"Sailormoon",new Effect(sailormoon, ed.Find(e => e.Name == "Sailormoon"))},
                {"GhostBusters",new Effect(gb, ed.Find(e => e.Name == "GhostBusters"))},
                {"Zelda",new Effect(zelda, ed.Find(e => e.Name == "Zelda"))},
                {"Tardis",new Effect(tardis, ed.Find(e => e.Name == "Tardis"))},
                {"F**k",new Effect(f**k, ed.Find(e => e.Name == "F**k"))},
                {"SilverFang",new Effect(silverFang, ed.Find(e => e.Name == "SilverFang"))},
                {"MoraT",new Effect(mt, ed.Find(e => e.Name == "MoraT"))},
                {"Ronja",new Effect(ronja, ed.Find(e => e.Name == "Ronja"))},
                {"Emil",new Effect(emil, ed.Find(e => e.Name == "Emil"))},
                {"Djungelboken",new Effect(djungelboken, ed.Find(e => e.Name == "Djungelboken"))},
                {"Fabbe",new Effect(fabbe, ed.Find(e => e.Name == "Fabbe"))},
                {"Drink",new Effect(drink, ed.Find(e => e.Name == "Drink"))},
                {"Frozen",new Effect(drink, ed.Find(e => e.Name == "Frozen"))}
            };

            runEffectInMonth = new Dictionary<string, List<objdata>>();

            string[] months = Util.monthlist();
            int counter;
            foreach (KeyValuePair<string, Effect> pair in effects)
            {
                counter = 0;
                foreach (bool b in pair.Value.RunAllowedlist)
                {
                    if (b == true)
                    {
                        if (!runEffectInMonth.ContainsKey(months[counter]))
                        {
                            runEffectInMonth.Add(months[counter], new List<objdata>());
                        }

                        runEffectInMonth[months[counter]].Add(new objdata(pair.Key, pair.Value.Vetolist[counter], pair.Value.Priolist[counter], pair.Value.Runslist[counter]));
                    }
                    counter++;
                }
            }

            clock.NewDate += clock_NewDate; // Event listener

            if (ch.CrashDialogResult == System.Windows.Forms.DialogResult.Yes)
            {
                clock.clock = ch.CrashClock;
            }

            string name, date, type;
            // Event dates setup
            foreach (var item in XMLEvents.Descendants("event"))
            {
                name = item.Element("name").Value;
                date = item.Element("date").Value;
                type = item.Element("type").Value.ToLower();
                EventItem ei = new EventItem(name, type, date);
                if (!events.ContainsKey(date))
                {
                    List<EventItem> list = new List<EventItem>(); // seems most bad in my eyes...
                    events.Add(date, list);
                }

                for (int i = 0; i < events[date].Count; i++)
                {
                    EventItem e = events[date][i];
                    if ("birthday".Equals(e.Type) && "birthday".Equals(ei.Type))
                    {
                        e.Name += "\n\n" + ei.Name;
                        events[date][i] = e;
                    }
                }
                events[date].Add(ei);
                name = date = type = string.Empty;
            }

            // this needs to be fixed nicer...
            if (events.ContainsKey(ClockEnd.ToShortDateString()))
            {
                events[ClockEnd.ToShortDateString()].Clear(); // force this to be top..
                events[ClockEnd.ToShortDateString()].Add( new EventItem("outro", "outro", ClockEnd.ToShortDateString()) );
            }
            else
            {
                events.Add(ClockEnd.ToShortDateString(), new List<EventItem>() { new EventItem("outro", "outro", ClockEnd.ToShortDateString()) });
            }

            // Random effects on dates with no effects and check against new list of allowed things for them...
            DateTime dt = ClockStart;
            bool star = (Util.Rnd.Next(0, 1000) < 500 ? true:false); // make this random at the start too?
            int num = 0;

            while (dt <= ClockEnd)
            {
                date = dt.ToShortDateString();
                if (!events.ContainsKey(date))
                {
                    EventItem ei;

                    if (num == 0 || num == 1)
                    {
                        ei = new EventItem("starfield", "random", date);
                    }
                    else
                    {
                        //ei = new EventItem(randomEvent[Util.Rnd.Next(1, randomEvent.Count)], "random", date);

                        string month = "";
                        if (dt != null)
                            month = dt.Month.ToString();

                        switch (month)
                        {
                            case "1": month = "jan"; break;
                            case "2": month = "feb"; break;
                            case "3": month = "mar"; break;
                            case "4": month = "apr"; break;
                            case "5": month = "maj"; break;
                            case "6": month = "jun"; break;
                            case "7": month = "jul"; break;
                            case "8": month = "aug"; break;
                            case "9": month = "sep"; break;
                            case "10": month = "okt"; break;
                            case "11": month = "nov"; break;
                            case "12": month = "dec"; break;
                        }//switch

                        if (runEffectInMonth.ContainsKey(month))
                        {
                            List<objdata> mobj = runEffectInMonth[month];

                            List<objdata> vetolist = new List<objdata>();
                            List<objdata> novetolist = new List<objdata>();

                            foreach (objdata n in mobj)
                            {

                                if ("Quiz".Equals(n.Name) && eventnum == 4)
                                {
                                    n.vetoAgain();
                                    eventnum = 0;
                                }

                                if (n.Veto == true)
                                {
                                    if (n.Runs > 0)
                                        vetolist.Add(n);
                                }
                                else
                                {
                                    if (n.Runs > 0)
                                        novetolist.Add(n);
                                }
                            }

                            vetolist.Sort();
                            novetolist.Sort();

                            if (vetolist.Count > 0)
                            {
                                ei = new EventItem(vetolist[0].Name, "random", date);
                                vetolist[0].noMoreVeto();
                            }
                            else if (novetolist.Count > 0)
                            {
                                ei = new EventItem(novetolist[0].Name, "random", date);
                                novetolist[0].decRuns();
                                if (eventnum < 4)
                                    eventnum++;
                            }
                            else
                            {
                                ei = new EventItem(randomEvent[Util.Rnd.Next(1, randomEvent.Count)], "random", date);
                            }
                        }
                        else
                        {
                            ei = new EventItem(randomEvent[Util.Rnd.Next(1, randomEvent.Count)], "random", date);
                        }
                    }

                    num++;
                    if (num == 3)
                    {
                        num = 0;
                    }
                    ei = new EventItem("Self", "random", date); // this is for debuging new events
                    events.Add(date, new List<EventItem>());
                    events[date].Add(ei);
                }

                dt = dt.AddDays(1);
                date = string.Empty;
            }
        }
        private void SetupTextures()
        {
            UnloadAllTextures();

            foreach (System.Collections.Generic.KeyValuePair <string, string> tex in skin.TexturePaths)
            {
                try
                {
                    if (!textures.ContainsKey(tex.Key))
                    {
                        textures.Add(tex.Key, OpenTkTextureLoadFuncs.LoadTexture(tex.Value));
                    }
                    //else
                    //{
                    //    OpenTkTextureLoadFuncs.UnloadTexture(textures[tex.Key]);
                    //    textures[tex.Key] = OpenTkTextureLoadFuncs.LoadTexture(tex.Value);
                    //}
                }
                catch
                {
                    SkinnedMessageBox.Show(skin, DialogResMgr.GetString("MissingTextureError") + "\n(" + tex.Value + ")", "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Stop();
                }
            }


            // create an empty texture for using in otherwise unloaded chara icon textures
            // this avoids needing to check for their existence in the rendering loop
            int emptytex = OpenTkTextureLoadFuncs.LoadTransparentRGBATexture();

            for (int i = 0; i < charaicons.Length; i++)
            {
                string iconkey = "spr_Charaicon" + i.ToString();
                string icontex = charaicons[i].ImagePath;

                string typestr   = (charaicons[i].Type + 1).ToString();
                string raritystr = (charaicons[i].Rarity + 1).ToString();

                string frontkey = "sprCharafront" + typestr + raritystr;
                string fronttex = skin.RootDir + "/charaimg/icon" + typestr + "_rare" + raritystr + "_front.png";

                string backkey = "sprCharaback" + typestr + raritystr;
                string backtex = skin.RootDir + "/charaimg/icon" + typestr + "_rare" + raritystr + "_bg.png";


                if (icontex != null && icontex.Length > 0)
                {
                    try
                    {
                        if (!textures.ContainsKey(iconkey))
                        {
                            textures.Add(iconkey, OpenTkTextureLoadFuncs.LoadTexture(icontex));
                        }
                    }
                    catch
                    {
                        SkinnedMessageBox.Show(skin, DialogResMgr.GetString("MissingTextureError") + "\n(" + icontex + ")", "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        Stop();
                    }
                }
                else
                {
                    // load an empty texture if no icon is specified
                    if (!textures.ContainsKey(iconkey))
                    {
                        textures.Add(iconkey, emptytex);
                    }
                }


                try
                {
                    if (!textures.ContainsKey(frontkey))
                    {
                        textures.Add(frontkey, OpenTkTextureLoadFuncs.LoadTexture(fronttex));
                    }
                }
                catch
                {
                    SkinnedMessageBox.Show(skin, DialogResMgr.GetString("MissingTextureError") + "\n(" + fronttex + ")", "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Stop();
                }

                try
                {
                    if (!textures.ContainsKey(backkey))
                    {
                        textures.Add(backkey, OpenTkTextureLoadFuncs.LoadTexture(backtex));
                    }
                }
                catch
                {
                    SkinnedMessageBox.Show(skin, DialogResMgr.GetString("MissingTextureError") + "\n(" + backtex + ")", "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Stop();
                }
            }


            // load empty textures for all unused front and back textures
            // not necessary, so commented (can be restored later if needed)
            //for (int i = 1; i < 4; i++)
            //{
            //    string typestr = i.ToString();

            //    for (int j = 1; j < 4; j++)
            //    {
            //        string raritystr = j.ToString();

            //        string frontkey = "sprCharafront" + typestr + raritystr;
            //        string backkey = "sprCharaback" + typestr + raritystr;

            //        if (!textures.ContainsKey(frontkey))
            //            textures.Add(frontkey, emptytex);

            //        if (!textures.ContainsKey(backkey))
            //            textures.Add(backkey, emptytex);
            //    }
            //}
        }
Esempio n. 59
0
        /// <summary>
        /// Gets the CAML query for well book summary pages.
        /// </summary>
        /// <returns> CAML query for well book summary pages.</returns>
        private string GetCAMLQueryForWellBookSummaryPages()
        {
            string strCamlQuery = string.Empty;
            StringBuilder sbChapterId = new StringBuilder();
            DataTable dtListDetails = null;
            string strTerminated = string.Empty;
            if (!ActiveStatus)
                strTerminated = STATUS_TERMINATED;
            else
                strTerminated = STATUS_ACTIVE;

            string strbookId = HttpContext.Current.Request.QueryString["BookId"];
            string wellbookStatus = HttpContext.Current.Request.QueryString["pageStatus"];
            string strPageOnwer = HttpContext.Current.Request.QueryString["pageOwner"];
            if (string.IsNullOrEmpty(strbookId))
                return string.Empty;
            objCommonBLL = new CommonBLL();
            strCamlQuery = @"<Where><Eq><FieldRef Name='Book_ID' /><Value Type='Number'>" +
             strbookId + "</Value></Eq></Where>";
            dtListDetails = objCommonBLL.ReadList(strSiteURL, CHAPTERLIST, strCamlQuery);
            if (dtListDetails != null && dtListDetails.Rows.Count > 0)
            {
                dicChatperDetail = new System.Collections.Generic.Dictionary<string, string>();

                for (int intRowIndex = 0; intRowIndex < dtListDetails.Rows.Count; intRowIndex++)
                {
                    if (!dicChatperDetail.ContainsKey(Convert.ToString(dtListDetails.Rows[intRowIndex]["ID"])))
                    {
                        dicChatperDetail.Add(Convert.ToString(dtListDetails.Rows[intRowIndex]["ID"]), Convert.ToString(dtListDetails.Rows[intRowIndex]["Title"]));
                        sbChapterId.Append(Convert.ToString(dtListDetails.Rows[intRowIndex]["ID"]));
                        sbChapterId.Append(";");
                    }
                }
                strCamlQuery = CreateCAMLQueryForSetOfCondtion(sbChapterId.ToString(), "Chapter_ID", "Number");
                sbChapterId.Remove(0, sbChapterId.Length);
                sbChapterId.Append(strCamlQuery);
                if (strPageOnwer.Equals("All") && wellbookStatus.Equals("Total"))
                {
                    sbChapterId.Append("<Eq><FieldRef Name='Sign_Off_Status' /><Value Type='Choice'>" + strSignedOffStatus + "</Value></Eq></And>");
                    sbChapterId.Append("<Eq><FieldRef Name='Terminate_Status' /><Value Type='Choice'>" + strTerminated + "</Value></Eq></And></Where>");
                    sbChapterId.Insert(0, "<Where><And><And>");
                }
                else if (!strPageOnwer.Equals("All") && wellbookStatus.Equals("Total"))
                {
                    sbChapterId.Append("<Eq><FieldRef Name='Sign_Off_Status' /><Value Type='Choice'>" + strSignedOffStatus + "</Value></Eq></And>");
                    sbChapterId.Append("<Eq><FieldRef Name='Owner' /><Value Type='Text'>" + strPageOnwer + "</Value></Eq></And>");
                    sbChapterId.Append("<Eq><FieldRef Name='Terminate_Status' /><Value Type='Choice'>" + strTerminated + "</Value></Eq></And></Where>");
                    sbChapterId.Insert(0, "<Where><And><And><And>");
                }
                else if (strPageOnwer.Equals("All") && !wellbookStatus.Equals("Total"))
                {
                    if (wellbookStatus.Equals("SignedOff"))
                    {
                        sbChapterId.Append("<Eq><FieldRef Name='Sign_Off_Status' /><Value Type='Choice'>Yes</Value></Eq></And>");
                    }
                    else if (wellbookStatus.Equals("NotSignedOff"))
                    {
                        sbChapterId.Append("<Eq><FieldRef Name='Sign_Off_Status' /><Value Type='Choice'>No</Value></Eq></And>");
                    }
                    else if (wellbookStatus.Equals("Empty"))
                    {
                        sbChapterId.Append("<Eq><FieldRef Name='Sign_Off_Status' /><Value Type='Choice'>" + strSignedOffStatus + "</Value></Eq></And>");
                        //need to add here also?
                        sbChapterId.Append("<Eq><FieldRef Name='Empty' /><Value Type='Choice'>Yes</Value></Eq></And>");
                    }

                    sbChapterId.Append("<Eq><FieldRef Name='Terminate_Status' /><Value Type='Choice'>" + strTerminated + "</Value></Eq></And></Where>");
                    if (wellbookStatus.Equals("Empty"))
                        sbChapterId.Insert(0, "<Where><And><And><And>");
                    else
                        sbChapterId.Insert(0, "<Where><And><And>");
                }
                else if (!strPageOnwer.Equals("All") && !wellbookStatus.Equals("Total"))
                {

                    if (wellbookStatus.Equals("SignedOff"))
                    {
                        sbChapterId.Append("<Eq><FieldRef Name='Sign_Off_Status' /><Value Type='Choice'>Yes</Value></Eq></And>");
                    }
                    else if (wellbookStatus.Equals("NotSignedOff"))
                    {
                        sbChapterId.Append("<Eq><FieldRef Name='Sign_Off_Status' /><Value Type='Choice'>No</Value></Eq></And>");
                    }
                    else if (wellbookStatus.Equals("Empty"))
                    {
                        sbChapterId.Append("<Eq><FieldRef Name='Sign_Off_Status' /><Value Type='Choice'>" + strSignedOffStatus + "</Value></Eq></And>");
                        sbChapterId.Append("<Eq><FieldRef Name='Empty' /><Value Type='Choice'>Yes</Value></Eq></And>");
                    }

                    sbChapterId.Append("<Eq><FieldRef Name='Owner' /><Value Type='Text'>" + strPageOnwer + "</Value></Eq></And>");

                    sbChapterId.Append("<Eq><FieldRef Name='Terminate_Status' /><Value Type='Choice'>" + strTerminated + "</Value></Eq></And></Where>");
                    if (wellbookStatus.Equals("Empty"))
                        sbChapterId.Insert(0, "<Where><And><And><And><And>");
                    else
                        sbChapterId.Insert(0, "<Where><And><And><And>");
                }
                sbChapterId.Insert(0, "<OrderBy><FieldRef Name='Connection_Type' /></OrderBy>");
            }
            if (dtListDetails != null)
            {
                dtListDetails.Dispose();
            }
            return sbChapterId.ToString();
        }
 // Dictionary`2::ContainsKey can be used with conditional code.
 public void Good9(System.Collections.Generic.Dictionary <string, bool> d, string name)
 {
     ConditionalCall(d.ContainsKey(name));
 }