Exemple #1
0
        private void b_format_change_file_Click(object sender, EventArgs e)
        {
            if ((null != m_sel_header) && (0 < m_sel_subitems.Count))
            {
                if (2 > m_sel_subitems.Count)
                {
                    ListViewItem.ListViewSubItem lsi = m_sel_subitems[0];

                    conv_core.cFormat    fmt = m_sel_header.Tag as conv_core.cFormat;
                    conv_core.cImageFile img = lsi.Tag as conv_core.cImageFile;

                    dw_save.Title            = "Change file location";
                    dw_save.InitialDirectory = Path.GetDirectoryName(img.path);
                    dw_save.Filter           = fmt.desc + "|*." + fmt.ext;
                    dw_save.FileName         = Path.GetFileName(img.path);

                    switch (dw_save.ShowDialog(this))
                    {
                    case DialogResult.OK:
                        string new_path = conv_core.workbench.relative_path(t_base_dir.Text, dw_save.FileName);
                        if ((0 < new_path.Length) && (new_path != lsi.Text))
                        {
                            img.path = dw_save.FileName.ToLower();
                            lsi.Text = new_path;

                            t_mod.Enabled = true;
                            m_sel_header.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                        }
                        ;
                        break;
                    }
                    ;
                }
                else
                {
                    dw_dir.Description  = "Select new files location.";
                    dw_dir.SelectedPath = Path.GetDirectoryName((m_sel_subitems[0].Tag as conv_core.cImageFile).path);

                    switch (dw_dir.ShowDialog(this))
                    {
                    case DialogResult.OK:
                        foreach (ListViewItem.ListViewSubItem lsi in m_sel_subitems)
                        {
                            conv_core.cImageFile img = lsi.Tag as conv_core.cImageFile;
                            string file_name         = Path.GetFileName(img.path);
                            string new_path          = conv_core.workbench.relative_path(t_base_dir.Text, dw_dir.SelectedPath + "\\" + file_name);
                            if ((0 < new_path.Length) && (new_path != lsi.Text))
                            {
                                img.path = dw_dir.SelectedPath.ToLower() + "\\" + file_name;
                                lsi.Text = new_path;
                            }
                            ;
                        }
                        ;

                        t_mod.Enabled = true;
                        m_sel_header.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                        break;
                    }
                    ;
                };
            }
            ;
        }
Exemple #2
0
        private void FillData()
        {
            if (bLoading)
            {
                return;
            }

            lvwReport.SuspendLayout();
            lvwReport.Items.Clear();

            DateTime  recordsMaxDate  = dblayer.FillReportDataMaxDate(cmbYears.Text);
            int       recordsMaxMonth = recordsMaxDate.Month + 1;
            ArrayList records         = dblayer.FillReportData(cmbYears.Text);

            // Adds a new group that has a left-aligned header
            for (int i = 0; i < records.Count; i++)
            {
                ArrayList record           = (ArrayList)records[i];
                String    GroupName        = record[3].ToString();
                String    NameOfCompany    = record[0].ToString();
                DateTime  LetkufaUd        = DateTime.Parse(record[1].ToString(), new System.Globalization.CultureInfo("en-AU", false));
                Double    SchumKolelelMaam = Double.Parse(record[2].ToString());

                ListViewGroup lvg = new ListViewGroup(GroupName);
                lvg.Name = GroupName;
                if (!lvwReport.Groups.Contains(lvg))
                {
                    lvwReport.Groups.Add(lvg);
                }

                //if (lvwReport.Items.Find(CompanyName.Replace(" ", "_"), true).Length == 0)
                ListViewItem foundItem = null;
                try
                {
                    foundItem = lvwReport.FindItemWithText(NameOfCompany, false, 0, true);
                }
                catch (Exception)
                {
                }

                if (foundItem == null)
                {
                    foundItem = lvwReport.Items.Add(NameOfCompany);
                }

                foundItem.UseItemStyleForSubItems = false;
                foundItem.Group = lvg;

                for (int j = 1; j < lvwReport.Columns.Count; j++)
                {
                    ListViewItem.ListViewSubItem lviSbi = foundItem.SubItems.Add("0.00");
                    lviSbi.Tag       = (Double)0;
                    lviSbi.ForeColor = Color.LightGray;
                }

                if (cmbYears.Text == LetkufaUd.Year.ToString()) //if (DateTime.Now.Year == LetkufaUd.Year)
                {
                    Double monthValue = (Double)foundItem.SubItems[LetkufaUd.Month + 1].Tag;
                    foundItem.SubItems[LetkufaUd.Month + 1].Tag  = (monthValue + SchumKolelelMaam);
                    foundItem.SubItems[LetkufaUd.Month + 1].Text = string.Format("{0:N2}", (Double)foundItem.SubItems[LetkufaUd.Month + 1].Tag);

                    if (((Double)foundItem.SubItems[LetkufaUd.Month + 1].Tag) > 0)
                    {
                        foundItem.SubItems[LetkufaUd.Month + 1].ForeColor = Color.Black;
                    }
                }
            }

            foreach (ListViewItem lvi in lvwReport.Items)
            {
                Double yearValue = 0;

                for (int i = 1; i < 12; i++)
                {
                    yearValue += (Double)lvi.SubItems[i].Tag;
                }

                lvi.SubItems[13].Tag = yearValue;
                lvi.SubItems[14].Tag = yearValue / 12;

                lvi.SubItems[13].Text = string.Format("{0:N2}", yearValue);
                lvi.SubItems[14].Text = string.Format("{0:N2}", yearValue / recordsMaxMonth);


                if (yearValue > 0)
                {
                    lvi.SubItems[13].ForeColor = Color.Black;
                    lvi.SubItems[14].ForeColor = Color.Black;
                }
            }
            lvwReport.ResumeLayout();
        }
        private void newRM(string torrentPath)
        {
            //         try
            //         {

            //make this user proof! :P
            //disable the new RM tool bar button
            toolStripButton1.Enabled = false;

            //disable the new RM menu item
            newRMToolStripMenuItem.Enabled = false;

            //global counter for RMs
            Program.RMcount++;

            //Initillize the Item and it's sub items... so that this will go on gracefuly :)
            //add a new item to the list this will be properly modified by the Form1 UI later

            //temp sub item
            ListViewItem.ListViewSubItem tmpSitem;

            listMain.Items.Add(new ListViewItem());

            //set the items color accoring to the last time's set color...
            if (listMain.Items.Count == 1)
            {
                listMain.Items[listMain.Items.Count - 1].BackColor = Color.AliceBlue;
            }
            else
            {
                if (listMain.Items[listMain.Items.Count - 2].BackColor == Color.AliceBlue)
                {
                    //this is the current last item...
                    listMain.Items[listMain.Items.Count - 1].BackColor = Color.White;
                }
                else
                {
                    listMain.Items[listMain.Items.Count - 1].BackColor = Color.AliceBlue;
                }
            }
            //fill the item with sub items
            for (int a = 0; a < 14; a++)
            {
                tmpSitem = new ListViewItem.ListViewSubItem();
                listMain.Items[listMain.Items.Count - 1].SubItems.Add(tmpSitem);
            }

            //create and add to the collection...
            tempRM = new TorrentSession(Program.RMcount);
            Program.rmCol.Add(tempRM);



            //show the New Torrent UI ;)
            Program.tempConUI = new rm2.UI.TorrerntSettingsUI();
            Program.tempConUI.currentRMIns = Program.rmCol[Program.RMcount];
            Program.tempConUI.Show();
            if (torrentPath != null)
            {
                Program.tempConUI.loadTorrentFileInfo(torrentPath, true);
            }


            //ListViewItem item = listMain.Items.Add(file.Name);
            // listMain.Items[Program.RMcount].SubItems.Add(Program.rmCol[Program.RMcount].currentTorrent.tracker);
            // listMain.Items[Program.RMcount].Text = Program.RMcount.ToString();
            // listMain.Items[Program.RMcount].SubItems[0].Text = Program.rmCol[Program.RMcount].currentTorrent.tracker;


            //       }
            //       catch (Exception e)
            //       {
            //           MessageBox.Show(e.ToString(), "clsMain>newRM() error!");
            //       }
        }
Exemple #4
0
 public static void Lazify(this ListViewItem.ListViewSubItem subItem)
 {
     subItem.Tag  = subItem.Text;
     subItem.Text = subItem.Text.Substring(0, Math.Min(DefaultLength, subItem.Text.Length));
 }
Exemple #5
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == true)
            {
                try
                {
                    String ketqua = "";

                    try
                    {
                        id_card = serialPort1.ReadExisting();
                        if (id_card.Length != 0)
                        {
nhay_toi_day_khi_di_vao:    // label goto

                            if (id_card.Length == 11)
                            {
                                id_card = id_card.Substring(0, 8);

                                string sql         = "Select * from customer1 where Id_card= '" + id_card + "'";
                                int    customer_id = getID(sql);
                                String query       = "SELECT status.id FROM status where customer_id = '" + customer_id + "' and status.status_customer = 0 ";
                                int    statusID    = getID(query);
                                if (statusID != 0)
                                {
                                    String message = Query_Data_MySQL.updateStatus(getID(query));
                                    serialPort1.WriteLine("#2:Good bye!|");    //dieu khien servo mo cua
                                }
                                else
                                {
                                    goto nhay_toi_day_khi_di_vao;
                                }
                            }
                            else
                            {
                                if (Query_Data_MySQL.checkPark())
                                {
                                    serialPort1.WriteLine("#3:Sorry!Da het cho dau!|"); //dieu khien servo mo cua
                                    return;
                                }
                                id_card = id_card.Substring(0, 8);
                                using (SqlConnection conn = new SqlConnection(ConnecttionString.connecttionString))
                                {
                                    conn.Open();
                                    try
                                    {
                                        // String query = "SELECT status.id FROM status INNER JOIN customer1 ON customer1.Id_card = '" + id_card + "' and status.status_customer = 0 ";
                                        // if (getID(query) == 0)

                                        string sql = "Select * from customer1 where Id_card= '" + id_card + "'";
                                        // Tạo một đối tượng Command.
                                        SqlCommand cmd = new SqlCommand(sql, conn);
                                        using (DbDataReader reader = cmd.ExecuteReader())
                                        {
                                            if (reader.HasRows)
                                            {
                                                while (reader.Read())
                                                {
                                                    // Chỉ số (index) của cột ID trong câu lệnh SQL.
                                                    int      Index_id    = reader.GetOrdinal("id");         //
                                                    int      id          = reader.GetInt32(Index_id);
                                                    int      startTime   = reader.GetOrdinal("Start_Time"); //
                                                    DateTime startTimeKH = reader.GetDateTime(startTime);

                                                    // Chỉ số (index) của cột Emp_ID trong câu lệnh SQL.
                                                    int      endTime   = reader.GetOrdinal("End_Time");
                                                    DateTime endTimeKH = reader.GetDateTime(endTime);
                                                    if (checkActive(startTimeKH, endTimeKH))
                                                    {
                                                        serialPort1.WriteLine("#3:The da het han!|"); //dieu khien servo mo cua
                                                        break;
                                                    }
                                                    String query = "SELECT status.id FROM status where customer_id = '" + id + "' and status.status_customer = 0 ";
                                                    // Chỉ số (index) của cột Emp_ID trong câu lệnh SQL.
                                                    if (getID(query) != 0)
                                                    {
                                                        serialPort1.WriteLine("#3:Xe Dang Gui!|");
                                                        conn.Close();
                                                        return;
                                                    }
                                                    // them vao bang trang thai
                                                    String       message = Query_Data_MySQL.insertStatus(id);
                                                    ListViewItem LVItem  = new ListViewItem(stt.ToString());
                                                    // Chỉ số (index) của cột Emp_ID trong câu lệnh SQL.
                                                    int nameIndex = reader.GetOrdinal("Name");     // 0
                                                                                                   // Cột Emp_No có index = 1.
                                                    string name = reader.GetString(nameIndex);
                                                    ListViewItem.ListViewSubItem LVSItem1 = new ListViewItem.ListViewSubItem(LVItem, name);
                                                    int    id_theIndex = reader.GetOrdinal("Bien_so_xe"); // 2
                                                    string id_the      = reader.GetString(id_theIndex);
                                                    ListViewItem.ListViewSubItem LVSItem2 = new ListViewItem.ListViewSubItem(LVItem, id_the);
                                                    int    phone       = reader.GetOrdinal("Phone");// 2
                                                    string phoneString = reader.GetString(phone);
                                                    ListViewItem.ListViewSubItem LVSItem3 = new ListViewItem.ListViewSubItem(LVItem, phoneString);
                                                    int    cmnn       = reader.GetOrdinal("CMNN");// 2
                                                    string cmnnString = reader.GetString(cmnn);
                                                    ListViewItem.ListViewSubItem LVSItem4 = new ListViewItem.ListViewSubItem(LVItem, cmnnString);
                                                    LVItem.SubItems.Add(LVSItem1);
                                                    LVItem.SubItems.Add(LVSItem2);
                                                    LVItem.SubItems.Add(LVSItem3);
                                                    LVItem.SubItems.Add(LVSItem4);
                                                    listView1.Items.Add(LVItem);

                                                    ketqua = name + "," + id_the;
                                                    stt++;
                                                }
                                            }
                                        }
                                        if (ketqua.Length >= 5)
                                        {
                                            serialPort1.WriteLine("#1:" + ketqua + "|");     //dieu khien servo mo cua
                                        }
                                        else
                                        {
                                            serialPort1.WriteLine("#3:Chua Dang Ky!|");     //dieu khien servo mo cua
                                        }
                                    }
                                    catch (Exception en)
                                    {
                                        serialPort1.WriteLine("#3:Chua Dang Ky123!|"); //dieu khien servo mo cua
                                    }
                                    conn.Close();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("hello pham duy thanh");
                }
            }
        }
Exemple #6
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            uint walletHeight = 0;

            if (Program.CurrentWallet != null)
            {
                walletHeight = (Program.CurrentWallet.WalletHeight > 0) ? Program.CurrentWallet.WalletHeight - 1 : 0;
            }

            lbl_height.Text = $"{walletHeight}/{Blockchain.Singleton.Height}/{Blockchain.Singleton.HeaderHeight}";

            lbl_count_node.Text = LocalNode.Singleton.ConnectedCount.ToString();
            TimeSpan persistence_span = DateTime.UtcNow - persistence_time;

            if (persistence_span < TimeSpan.Zero)
            {
                persistence_span = TimeSpan.Zero;
            }
            if (persistence_span > Blockchain.TimePerBlock)
            {
                toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
            }
            else
            {
                toolStripProgressBar1.Value = persistence_span.Seconds;
                toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
            }
            if (Program.CurrentWallet != null)
            {
                if (Program.CurrentWallet.WalletHeight <= Blockchain.Singleton.Height + 1)
                {
                    if (balance_changed)
                    {
                        using (Snapshot snapshot = Blockchain.Singleton.GetSnapshot())
                        {
                            IEnumerable <Coin> coins             = Program.CurrentWallet?.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent)) ?? Enumerable.Empty <Coin>();
                            Fixed8             bonus_available   = snapshot.CalculateBonus(Program.CurrentWallet.GetUnclaimedCoins().Select(p => p.Reference));
                            Fixed8             bonus_unavailable = snapshot.CalculateBonus(coins.Where(p => p.State.HasFlag(CoinState.Confirmed) && p.Output.AssetId.Equals(Blockchain.GoverningToken.Hash)).Select(p => p.Reference), snapshot.Height + 1);
                            Fixed8             bonus             = bonus_available + bonus_unavailable;
                            var assets = coins.GroupBy(p => p.Output.AssetId, (k, g) => new
                            {
                                Asset = snapshot.Assets.TryGet(k),
                                Value = g.Sum(p => p.Output.Value),
                                Claim = k.Equals(Blockchain.UtilityToken.Hash) ? bonus : Fixed8.Zero
                            }).ToDictionary(p => p.Asset.AssetId);
                            if (bonus != Fixed8.Zero && !assets.ContainsKey(Blockchain.UtilityToken.Hash))
                            {
                                assets[Blockchain.UtilityToken.Hash] = new
                                {
                                    Asset = snapshot.Assets.TryGet(Blockchain.UtilityToken.Hash),
                                    Value = Fixed8.Zero,
                                    Claim = bonus
                                };
                            }
                            var balance_ans = coins.Where(p => p.Output.AssetId.Equals(Blockchain.GoverningToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                            var balance_anc = coins.Where(p => p.Output.AssetId.Equals(Blockchain.UtilityToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                            foreach (ListViewItem item in listView1.Items)
                            {
                                UInt160 script_hash = item.Name.ToScriptHash();
                                Fixed8  ans         = balance_ans.ContainsKey(script_hash) ? balance_ans[script_hash] : Fixed8.Zero;
                                Fixed8  anc         = balance_anc.ContainsKey(script_hash) ? balance_anc[script_hash] : Fixed8.Zero;
                                item.SubItems["ans"].Text = ans.ToString();
                                item.SubItems["anc"].Text = anc.ToString();
                            }
                            foreach (AssetState asset in listView2.Items.OfType <ListViewItem>().Select(p => p.Tag as AssetState).Where(p => p != null).ToArray())
                            {
                                if (!assets.ContainsKey(asset.AssetId))
                                {
                                    listView2.Items.RemoveByKey(asset.AssetId.ToString());
                                }
                            }
                            foreach (var asset in assets.Values)
                            {
                                string value_text = asset.Value.ToString() + (asset.Asset.AssetId.Equals(Blockchain.UtilityToken.Hash) ? $"+({asset.Claim})" : "");
                                if (listView2.Items.ContainsKey(asset.Asset.AssetId.ToString()))
                                {
                                    listView2.Items[asset.Asset.AssetId.ToString()].SubItems["value"].Text = value_text;
                                }
                                else
                                {
                                    string asset_name = asset.Asset.AssetType == AssetType.GoverningToken ? "NEO" :
                                                        asset.Asset.AssetType == AssetType.UtilityToken ? "NeoGas" :
                                                        asset.Asset.GetName();
                                    listView2.Items.Add(new ListViewItem(new[]
                                    {
                                        new ListViewItem.ListViewSubItem
                                        {
                                            Name = "name",
                                            Text = asset_name
                                        },
                                        new ListViewItem.ListViewSubItem
                                        {
                                            Name = "type",
                                            Text = asset.Asset.AssetType.ToString()
                                        },
                                        new ListViewItem.ListViewSubItem
                                        {
                                            Name = "value",
                                            Text = value_text
                                        },
                                        new ListViewItem.ListViewSubItem
                                        {
                                            ForeColor = Color.Gray,
                                            Name      = "issuer",
                                            Text      = $"{Strings.UnknownIssuer}[{asset.Asset.Owner}]"
                                        }
                                    }, -1, listView2.Groups["unchecked"])
                                    {
                                        Name = asset.Asset.AssetId.ToString(),
                                        Tag  = asset.Asset,
                                        UseItemStyleForSubItems = false
                                    });
                                }
                            }
                            balance_changed = false;
                        }
                    }
                    foreach (ListViewItem item in listView2.Groups["unchecked"].Items.OfType <ListViewItem>().ToArray())
                    {
                        ListViewItem.ListViewSubItem subitem = item.SubItems["issuer"];
                        AssetState             asset         = (AssetState)item.Tag;
                        CertificateQueryResult result;
                        if (asset.AssetType == AssetType.GoverningToken || asset.AssetType == AssetType.UtilityToken)
                        {
                            result = new CertificateQueryResult {
                                Type = CertificateQueryResultType.System
                            };
                        }
                        else
                        {
                            result = CertificateQueryService.Query(asset.Owner);
                        }
                        using (result)
                        {
                            subitem.Tag = result.Type;
                            switch (result.Type)
                            {
                            case CertificateQueryResultType.Querying:
                            case CertificateQueryResultType.QueryFailed:
                                break;

                            case CertificateQueryResultType.System:
                                subitem.ForeColor = Color.Green;
                                subitem.Text      = Strings.SystemIssuer;
                                break;

                            case CertificateQueryResultType.Invalid:
                                subitem.ForeColor = Color.Red;
                                subitem.Text      = $"[{Strings.InvalidCertificate}][{asset.Owner}]";
                                break;

                            case CertificateQueryResultType.Expired:
                                subitem.ForeColor = Color.Yellow;
                                subitem.Text      = $"[{Strings.ExpiredCertificate}]{result.Certificate.Subject}[{asset.Owner}]";
                                break;

                            case CertificateQueryResultType.Good:
                                subitem.ForeColor = Color.Black;
                                subitem.Text      = $"{result.Certificate.Subject}[{asset.Owner}]";
                                break;
                            }
                            switch (result.Type)
                            {
                            case CertificateQueryResultType.System:
                            case CertificateQueryResultType.Missing:
                            case CertificateQueryResultType.Invalid:
                            case CertificateQueryResultType.Expired:
                            case CertificateQueryResultType.Good:
                                item.Group = listView2.Groups["checked"];
                                break;
                            }
                        }
                    }
                }
                if (check_nep5_balance && persistence_span > TimeSpan.FromSeconds(2))
                {
                    UInt160[] addresses = Program.CurrentWallet.GetAccounts().Select(p => p.ScriptHash).ToArray();
                    foreach (string s in Settings.Default.NEP5Watched)
                    {
                        UInt160 script_hash = UInt160.Parse(s);
                        byte[]  script;
                        using (ScriptBuilder sb = new ScriptBuilder())
                        {
                            foreach (UInt160 address in addresses)
                            {
                                sb.EmitAppCall(script_hash, "balanceOf", address);
                            }
                            sb.Emit(OpCode.DEPTH, OpCode.PACK);
                            sb.EmitAppCall(script_hash, "decimals");
                            sb.EmitAppCall(script_hash, "name");
                            script = sb.ToArray();
                        }
                        ApplicationEngine engine = ApplicationEngine.Run(script);
                        if (engine.State.HasFlag(VMState.FAULT))
                        {
                            continue;
                        }
                        string     name     = engine.ResultStack.Pop().GetString();
                        byte       decimals = (byte)engine.ResultStack.Pop().GetBigInteger();
                        BigInteger amount   = ((VMArray)engine.ResultStack.Pop()).Aggregate(BigInteger.Zero, (x, y) => x + y.GetBigInteger());
                        if (amount == 0)
                        {
                            listView2.Items.RemoveByKey(script_hash.ToString());
                            continue;
                        }
                        BigDecimal balance    = new BigDecimal(amount, decimals);
                        string     value_text = balance.ToString();
                        if (listView2.Items.ContainsKey(script_hash.ToString()))
                        {
                            listView2.Items[script_hash.ToString()].SubItems["value"].Text = value_text;
                        }
                        else
                        {
                            listView2.Items.Add(new ListViewItem(new[]
                            {
                                new ListViewItem.ListViewSubItem
                                {
                                    Name = "name",
                                    Text = name
                                },
                                new ListViewItem.ListViewSubItem
                                {
                                    Name = "type",
                                    Text = "NEP-5"
                                },
                                new ListViewItem.ListViewSubItem
                                {
                                    Name = "value",
                                    Text = value_text
                                },
                                new ListViewItem.ListViewSubItem
                                {
                                    ForeColor = Color.Gray,
                                    Name      = "issuer",
                                    Text      = $"ScriptHash:{script_hash}"
                                }
                            }, -1, listView2.Groups["checked"])
                            {
                                Name = script_hash.ToString(),
                                UseItemStyleForSubItems = false
                            });
                        }
                    }
                    check_nep5_balance = false;
                }
            }
        }
Exemple #7
0
        // Adiciona o filme selecionado da lista de filmes a relação de filmes a ser locada //


        private void Metodo_Selecionar_Filmes()
        {
            bool FILME_VERIFICACAO = false;

            if (listView_Filmes_Disponiveis.SelectedItems.Count != 0)
            {
                for (int I = 0; I < listView_Relacao_Filmes.Items.Count; I++)
                {
                    if (listView_Relacao_Filmes.Items[I].Text == listView_Filmes_Disponiveis.SelectedItems[0].Text)
                    {
                        FILME_VERIFICACAO = true;
                        MessageBox.Show("Este Filme já foi SELECIONADO");
                    }
                }
            }

            if (listView_Filmes_Disponiveis.SelectedItems[0].SubItems[6].Text == "LOCADO")
            {
                FILME_VERIFICACAO = true;
                MessageBox.Show("Este fime já está locado");
            }



            if (listView_Filmes_Disponiveis.SelectedItems.Count != 0 && FILME_VERIFICACAO == false)
            {
                Filmes FILME_SELECIONADO = new Filmes(int.Parse(listView_Filmes_Disponiveis.SelectedItems[0].Text), listView_Filmes_Disponiveis.SelectedItems[0].SubItems[1].Text, listView_Filmes_Disponiveis.SelectedItems[0].SubItems[2].Text, listView_Filmes_Disponiveis.SelectedItems[0].SubItems[3].Text, listView_Filmes_Disponiveis.SelectedItems[0].SubItems[4].Text, listView_Filmes_Disponiveis.SelectedItems[0].SubItems[5].Text, listView_Filmes_Disponiveis.SelectedItems[0].SubItems[6].Text);

                ListViewItem CODIGO_FILMES = new ListViewItem(FILME_SELECIONADO.CODIGO.ToString());

                ListViewItem.ListViewSubItem TITULO_FILME = new ListViewItem.ListViewSubItem();

                ListViewItem.ListViewSubItem GENERO_FILME = new ListViewItem.ListViewSubItem();

                ListViewItem.ListViewSubItem CLASSIFICACAO_FILME = new ListViewItem.ListViewSubItem();

                ListViewItem.ListViewSubItem TIPO_MIDIA = new ListViewItem.ListViewSubItem();

                ListViewItem.ListViewSubItem CATALOGO_PRECO_FILME = new ListViewItem.ListViewSubItem();

                ListViewItem.ListViewSubItem VALOR_CATALOGO = new ListViewItem.ListViewSubItem();

                ListViewItem.ListViewSubItem DATA_DEVOLUCAO = new ListViewItem.ListViewSubItem();


                TITULO_FILME.Text = FILME_SELECIONADO.TITULO;
                CODIGO_FILMES.SubItems.Add(TITULO_FILME);

                GENERO_FILME.Text = FILME_SELECIONADO.GENERO;
                CODIGO_FILMES.SubItems.Add(GENERO_FILME);

                CLASSIFICACAO_FILME.Text = FILME_SELECIONADO.CLASSIFICACAO;
                CODIGO_FILMES.SubItems.Add(CLASSIFICACAO_FILME);

                TIPO_MIDIA.Text = FILME_SELECIONADO.TIPO_MIDIA;
                CODIGO_FILMES.SubItems.Add(TIPO_MIDIA);

                CATALOGO_PRECO_FILME.Text = FILME_SELECIONADO.CATEGORIA;
                CODIGO_FILMES.SubItems.Add(CATALOGO_PRECO_FILME);

                VALOR_CATALOGO.Text = DIC_CAT_PRECOS[FILME_SELECIONADO.CATEGORIA].ToString();
                CODIGO_FILMES.SubItems.Add(VALOR_CATALOGO);

                DATA_DEVOLUCAO.Text = DateTime.Now.AddDays(1).ToString("dd/MM/yyyy");
                CODIGO_FILMES.SubItems.Add(DATA_DEVOLUCAO);

                listView_Relacao_Filmes.Items.Add(CODIGO_FILMES);

                listView_Filmes_Disponiveis.SelectedItems[0].Remove();

                METODO_ATUALIZACAO_LOCACAO();
            }
        }
Exemple #8
0
        public void UpdateChangesDialog(List <ModChange> changeset, BackgroundWorker installWorker)
        {
            changeSet          = changeset;
            this.installWorker = installWorker;
            ChangesListView.Items.Clear();

            if (changeset == null)
            {
                return;
            }

            // We're going to split our change-set into two parts: updated/removed mods,
            // and everything else (which right now is installing mods, but we may have
            // other types in the future).

            changeSet = new List <ModChange>();
            changeSet.AddRange(changeset.Where(change => change.ChangeType == GUIModChangeType.Remove));
            changeSet.AddRange(changeset.Where(change => change.ChangeType == GUIModChangeType.Update));

            IEnumerable <ModChange> leftOver = changeset.Where(change => change.ChangeType != GUIModChangeType.Remove &&
                                                               change.ChangeType != GUIModChangeType.Update);

            // Now make our list more human-friendly (dependencies for a mod are listed directly
            // after it.)
            CreateSortedModList(leftOver);

            changeset = changeSet;

            foreach (var change in changeset)
            {
                if (change.ChangeType == GUIModChangeType.None)
                {
                    continue;
                }

                CkanModule   m    = change.Mod.ToModule();
                ListViewItem item = new ListViewItem()
                {
                    Text = Manager.Cache.IsMaybeCachedZip(m)
                        ? $"{m.name} {m.version} (cached)"
                        : $"{m.name} {m.version} ({m.download.Host ?? ""}, {CkanModule.FmtSize(m.download_size)})"
                };

                var sub_change_type = new ListViewItem.ListViewSubItem {
                    Text = change.ChangeType.ToString()
                };

                ListViewItem.ListViewSubItem description = new ListViewItem.ListViewSubItem();
                description.Text = change.Reason.Reason.Trim();

                if (change.ChangeType == GUIModChangeType.Update)
                {
                    description.Text = String.Format("Update selected by user to version {0}.", change.Mod.LatestVersion);
                }

                if (change.ChangeType == GUIModChangeType.Install && change.Reason is SelectionReason.UserRequested)
                {
                    description.Text = "New mod install selected by user.";
                }

                item.SubItems.Add(sub_change_type);
                item.SubItems.Add(description);
                ChangesListView.Items.Add(item);
            }
        }
        /// <summary>
        /// Refresh the properties list
        /// </summary>
        private void UpdatePropertiesList()
        {
            m_propertiesList.BeginUpdate();
            try
            {
                // Refresh columns
                m_propertiesList.Columns.Clear();
                m_propertiesList.Columns.Add("Attribute");
                foreach (var obj in m_selectControl.SelectedObjects)
                {
                    m_propertiesList.Columns.Add(obj.Name);
                }

                // Prepare properties list
                m_propertiesList.Groups.Clear();
                var items = new List <ListViewItem>();
                foreach (var category in StaticProperties.AllCategories)
                {
                    var  group    = new ListViewGroup(category.DisplayName);
                    bool hasProps = false;

                    foreach (var prop in category)
                    {
                        // Checks whether we must display this property
                        bool visibleProperty = false;

                        // Some properties should be always visible (fitting, shields resists, etc)
                        if (m_forceShipsPropertyToBeVisible)
                        {
                            visibleProperty = prop.AlwaysVisibleForShips;
                        }

                        // Or we check whether any object has this property
                        if (!visibleProperty)
                        {
                            visibleProperty = m_selectControl.SelectedObjects.Any(x => x.Properties[prop].HasValue);
                        }

                        // Some properties should be hidden if they have the default value (sensor strenght, em damage, etc)
                        if (m_selectControl.SelectedObject.Properties[prop].HasValue && prop.HideIfDefault)
                        {
                            visibleProperty = (prop.DefaultValue != m_selectControl.SelectedObject.Properties[prop].Value.Value);
                        }

                        // Jump to next property if not visible
                        if (!visibleProperty)
                        {
                            continue;
                        }
                        hasProps = true;


                        // Retrieve the datas to put in the columns
                        var labels   = m_selectControl.SelectedObjects.Select(x => prop.GetLabelOrDefault(x)).ToArray();
                        var values   = m_selectControl.SelectedObjects.Select(x => prop.GetNumericValue(x)).ToArray();
                        var min      = values.Min();
                        var max      = values.Max();
                        var allEqual = values.All(x => x == min);
                        if (!prop.HigherIsBetter)
                        {
                            var temp = min;
                            min = max;
                            max = temp;
                        }

                        // Create the list view item
                        ListViewItem item = new ListViewItem(group);
                        item.ToolTipText = prop.Description;
                        item.Text        = prop.Name;
                        items.Add(item);

                        // Add the value for every ship
                        int index = 0;
                        foreach (var obj in m_selectControl.SelectedObjects)
                        {
                            // Create the subitem and choose its forecolor
                            var subItem = new ListViewItem.ListViewSubItem(item, labels[index]);
                            if (!allEqual)
                            {
                                if (values[index] == max)
                                {
                                    subItem.ForeColor = Color.DarkGreen;
                                }
                                else if (values[index] == min)
                                {
                                    subItem.ForeColor = Color.DarkRed;
                                }
                                item.UseItemStyleForSubItems = false;
                            }
                            else if (m_selectControl.SelectedObjects.Count > 1)
                            {
                                subItem.ForeColor            = Color.DarkGray;
                                item.UseItemStyleForSubItems = false;
                            }

                            item.SubItems.Add(subItem);
                            index++;
                        }
                    }

                    // Add properties
                    if (hasProps)
                    {
                        m_propertiesList.Groups.Add(group);
                    }
                }

                // Fetch the new items to the list view
                m_propertiesList.Items.Clear();
                m_propertiesList.Items.AddRange(items.ToArray());
                m_propertiesList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            }
            finally
            {
                m_propertiesList.EndUpdate();
            }
        }
Exemple #10
0
        private void buildList()
        {
            smallImageList.Images.Add(ZunTzu.Properties.Resources.ZunTzuBox);
            largeImageList.Images.Add(ZunTzu.Properties.Resources.ZunTzuBox);

            foreach (IGameBoxReference reference in controller.Model.GameLibrary.GameBoxes)
            {
                ListViewItem item = new ListViewItem();
                item.Font      = nameFont;
                item.ForeColor = Color.Blue;
                item.Tag       = reference;
                item.Name      = "name";
                item.Text      = reference.Name;

                if (reference.Copyright != null && reference.Copyright != "")
                {
                    ListViewItem.ListViewSubItem copyrightSubItem = new ListViewItem.ListViewSubItem();
                    copyrightSubItem.Font      = copyrightFont;
                    copyrightSubItem.ForeColor = Color.DarkGray;
                    copyrightSubItem.Name      = "copyright";
                    copyrightSubItem.Text      = "Copyright© " + reference.Copyright;
                    item.SubItems.Add(copyrightSubItem);
                }

                if (reference.Description != null && reference.Description != "")
                {
                    ListViewItem.ListViewSubItem descriptionSubItem = new ListViewItem.ListViewSubItem();
                    descriptionSubItem.Font = descriptionFont;
                    descriptionSubItem.Name = "description";
                    descriptionSubItem.Text = reference.Description;
                    item.SubItems.Add(descriptionSubItem);
                }

                if (reference.Icon != null)
                {
                    Bitmap iconImage = new Bitmap(48, 48, PixelFormat.Format16bppRgb565);

                    BitmapData bitmapData = iconImage.LockBits(
                        new Rectangle(0, 0, iconImage.Width, iconImage.Height),
                        ImageLockMode.WriteOnly,
                        PixelFormat.Format16bppRgb565);
                    byte[] iconBytes = reference.Icon;
                    unsafe {
                        byte *ptr = (byte *)bitmapData.Scan0;
                        for (int i = 0; i < iconBytes.Length; ++i)
                        {
                            *ptr++ = iconBytes[i];
                        }
                    }
                    iconImage.UnlockBits(bitmapData);

                    item.ImageIndex = largeImageList.Images.Count;
                    largeImageList.Images.Add(iconImage);
                }
                else
                {
                    item.ImageIndex = 0;
                }

                listView.Items.Add(item);
            }
        }
Exemple #11
0
 private void AddListViewSubItem(ListView listView, int itemIndex, string subItemText)
 {
     ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
     subItem.Text = subItemText;
     listView.Items[itemIndex].SubItems.Add(subItem);
 }
        public bool loadSigners()
        {
            bool checkCRL = Convert.ToBoolean(assinadorRegistry.GetValue("ConsultCRL"));

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

            this.Cursor = Cursors.WaitCursor;

            lstSigners.Items.Clear();
            lstSigners.Groups.Clear();

            if (lstDocuments.SelectedItems.Count > 0)
            {
                List <string> problematicFoundDocuments = new List <string>();
                Signers       commonSigners             = new Signers();

                List <X509Certificate2> nonconformitySigners = new List <X509Certificate2>();
                List <X509Certificate2> conformitySigners    = new List <X509Certificate2>();
                Hashtable certificatesList = new Hashtable();
                foreach (FileHistory filepath in selectedDocuments)
                {
                    try
                    {
                        loadDigitalSignature(filepath.NewPath);

                        if (digitalSignature.error)
                        {
                            if (digitalSignature.DocumentType.Equals(Types.XpsDocument))
                            {
                                digitalSignature.xpsDocument.Close();
                            }
                            else
                            {
                                digitalSignature.package.Close();
                            }
                            this.Cursor = Cursors.Arrow;
                            return(false);
                        }

                        invalidSignatures.Clear();
                        if (!digitalSignature.Validate())
                        {
                            invalidSignatures = digitalSignature.InvalidDigitalSignatureHolderNames;
                        }

                        ListViewGroup sigaturesGroup = new ListViewGroup(Path.GetFileName(filepath.NewPath));
                        lstSigners.Groups.Add(sigaturesGroup);

                        foreach (Signer signer in digitalSignature.signers)
                        {
                            string[] signature = new string[5];
                            signature[0] = signer.name;
                            signature[1] = signer.issuer;
                            signature[2] = signer.uri;
                            signature[3] = signer.date;
                            signature[4] = signer.serialNumber;

                            X509Certificate2 signatureCertificate = signer.signerCertificate;
                            if ((!nonconformitySigners.Contains(signatureCertificate)) && (!conformitySigners.Contains(signatureCertificate)))
                            {
                                if (!CertificateUtils.ValidateCertificate(signatureCertificate, checkCRL, false) ?? true)
                                {
                                    nonconformitySigners.Add(signatureCertificate);
                                }
                                else
                                {
                                    conformitySigners.Add(signatureCertificate);
                                }
                                certificatesList.Add(signatureCertificate, CertificateUtils.buildStatus);
                            }

                            X509ChainStatus chainStatus = new X509ChainStatus();
                            chainStatus = (X509ChainStatus)certificatesList[signatureCertificate];

                            ChainDocumentStatus chainDocumentStatus = new ChainDocumentStatus();
                            int signatureIcon;
                            if (!(invalidSignatures.Contains(signature[0]) && invalidSignatures.Contains(signature[1]) &&
                                  invalidSignatures.Contains(signature[2]) && invalidSignatures.Contains(signature[3])))
                            {
                                chainDocumentStatus = new ChainDocumentStatus(chainStatus, null);
                                if (nonconformitySigners.Contains(signatureCertificate))
                                {
                                    signatureIcon = 1;
                                }
                                else
                                {
                                    signatureIcon = 2;
                                }
                            }
                            else
                            {
                                signatureIcon       = 0;
                                chainDocumentStatus = new ChainDocumentStatus(chainStatus, ChainDocumentStatus.ChainDocumentStatusFlags.CorruptedDocument);
                            }

                            ListViewItem newSignerItem = new ListViewItem();    //INDEX
                            newSignerItem.Text       = signature[0].ToString(); //0 signer.name
                            newSignerItem.ImageIndex = signatureIcon;
                            newSignerItem.Group      = sigaturesGroup;
                            newSignerItem.SubItems.Add(signature[1]);           //1 signer.issuer
                            newSignerItem.SubItems.Add(signature[3]);           //2 signer.date
                            newSignerItem.SubItems.Add(filepath.NewPath);       //3 signer.path
                            newSignerItem.SubItems.Add(signature[4]);           //4 signer.serialNumber
                            newSignerItem.SubItems.Add(signature[2]);           //5 signer.URI
                            newSignerItem.SubItems.Add(filepath.OriginalPath);  //6 signer.originalPath

                            ListViewItem.ListViewSubItem chainSt = new ListViewItem.ListViewSubItem();
                            chainSt.Text = "";
                            chainSt.Tag  = (object)chainDocumentStatus;
                            newSignerItem.SubItems.Add(chainSt);                //7 Tag chainStatus

                            newSignerItem.Tag = (object)signatureCertificate;   //Tag signer.signerCertificate

                            lstSigners.Items.Add(newSignerItem);

                            if (lstSigners.Groups.Count == 1)
                            {
                                Signer sgn = new Signer();
                                sgn.name              = signature[0].ToString();
                                sgn.issuer            = signature[1].ToString();
                                sgn.serialNumber      = signature[4].ToString();
                                sgn.signerCertificate = signatureCertificate;
                                if (!commonSigners.Contains(sgn))
                                {
                                    commonSigners.Add(sgn);
                                }
                            }
                        }
                        Signers commonRecentlyFoundSigners = new Signers();
                        foreach (ListViewItem lst in sigaturesGroup.Items)
                        {
                            foreach (Signer sgn in commonSigners)
                            {
                                if (lst.SubItems[0].Text == sgn.name &&
                                    lst.SubItems[1].Text == sgn.issuer &&
                                    lst.SubItems[4].Text == sgn.serialNumber &&
                                    !commonRecentlyFoundSigners.Contains(sgn))
                                {
                                    commonRecentlyFoundSigners.Add(sgn);
                                }
                            }
                        }
                        commonSigners = commonRecentlyFoundSigners;
                    }
                    #region catch
                    catch (IOException)
                    {
                        if (MessageBox.Show("Erro ao abrir o documento " + System.IO.Path.GetFileName(filepath.NewPath) + ".\nCertifique-se de que o documento não foi movido ou está em uso por outra aplicação.\n\nDeseja retirá-lo da lista?", System.IO.Path.GetFileName(filepath.NewPath),
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    lstDocuments.Items.Remove(item);
                                }
                            }
                        }
                        else
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    item.Selected = false;
                                    if (lstDocuments.SelectedItems.Count > 0)
                                    {
                                        lstDocuments.FocusedItem = lstDocuments.SelectedItems[0];
                                    }
                                }
                            }
                        }
                    }
                    catch (FileFormatException)
                    {
                        if (MessageBox.Show("Erro ao abrir o documento " + System.IO.Path.GetFileName(filepath.NewPath) + ".\nSeu conteúdo está corrompido, talvez seja um arquivo temporário.\n\nDeseja retirá-lo da lista?", System.IO.Path.GetFileName(filepath.NewPath),
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    lstDocuments.Items.Remove(item);
                                }
                            }
                        }
                        else
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    item.Selected = false;
                                    if (lstDocuments.SelectedItems.Count > 0)
                                    {
                                        lstDocuments.FocusedItem = lstDocuments.SelectedItems[0];
                                    }
                                }
                            }
                        }
                    }
                    catch (ArgumentNullException)
                    {
                        if (MessageBox.Show("O Documento " + System.IO.Path.GetFileName(filepath.NewPath) + "não está disponível para abertura.\n\nDeseja retirá-lo da lista?", System.IO.Path.GetFileName(filepath.NewPath),
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    lstDocuments.Items.Remove(item);
                                }
                            }
                        }
                        else
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    item.Selected = false;
                                    if (lstDocuments.SelectedItems.Count > 0)
                                    {
                                        lstDocuments.FocusedItem = lstDocuments.SelectedItems[0];
                                    }
                                }
                            }
                        }
                    }
                    catch (OpenXmlPackageException)
                    {
                        if (MessageBox.Show("O Documento " + System.IO.Path.GetFileName(filepath.NewPath) + " não é um pacote Open XML válido.\n\nDeseja retirá-lo da lista?", System.IO.Path.GetFileName(filepath.NewPath),
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    lstDocuments.Items.Remove(item);
                                }
                            }
                        }
                        else
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    item.Selected = false;
                                    if (lstDocuments.SelectedItems.Count > 0)
                                    {
                                        lstDocuments.FocusedItem = lstDocuments.SelectedItems[0];
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        if (MessageBox.Show("Houve um problema na listagem do seguinte documento:\n " + System.IO.Path.GetFileName(filepath.NewPath) + "\n" + err.Message.Substring(0, err.Message.IndexOf(".") + 1) + "\n\nDeseja excluí-lo da lista?", System.IO.Path.GetFileName(filepath.NewPath),
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    lstDocuments.Items.Remove(item);
                                }
                            }
                        }
                        else
                        {
                            foreach (ListViewItem item in lstDocuments.Items)
                            {
                                if (item.SubItems[2].Text == filepath.NewPath)
                                {
                                    problematicFoundDocuments.Add(item.SubItems[2].Text);
                                    item.Selected = false;
                                    if (lstDocuments.SelectedItems.Count > 0)
                                    {
                                        lstDocuments.FocusedItem = lstDocuments.SelectedItems[0];
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }

                if (lstDocuments.SelectedItems.Count > 1)
                {
                    ListViewGroup commonSigaturesGroup = new ListViewGroup("commonSignatures", "Assinaturas em Comum");
                    lstSigners.Groups.Insert(0, commonSigaturesGroup);

                    foreach (Signer sig in commonSigners)
                    {
                        ListViewItem newCommonSignerItem = new ListViewItem();
                        newCommonSignerItem.Text  = sig.name;                    //0 signer.name
                        newCommonSignerItem.Group = commonSigaturesGroup;
                        newCommonSignerItem.SubItems.Add(sig.issuer);            //1 signer.issuer
                        newCommonSignerItem.SubItems.Add("");                    //2 signer.date
                        newCommonSignerItem.SubItems.Add("");                    //3 signer.path
                        newCommonSignerItem.SubItems.Add(sig.serialNumber);      //4 signer.serialNumber
                        newCommonSignerItem.SubItems.Add("");                    //5 signer.URI
                        newCommonSignerItem.SubItems.Add("");                    //6 signer.originalPath
                        newCommonSignerItem.Tag = (object)sig.signerCertificate; //Tag signer.signerCertificate

                        lstSigners.Items.Add(newCommonSignerItem);
                    }
                }
                selectedDocuments.Clear();
                foreach (ListViewItem lvi in lstDocuments.SelectedItems)
                {
                    FileHistory fh = new FileHistory(lvi.SubItems[3].Text, lvi.SubItems[2].Text);
                    selectedDocuments.Add(fh);
                }
            }
            if (lstDocuments.SelectedItems.Count > 0)
            {
                loadFileDescription();
                if (digitalSignature.DocumentType.Equals(Types.XpsDocument))
                {
                    digitalSignature.xpsDocument.Close();
                }
                else
                {
                    digitalSignature.package.Close();
                }
            }
            else if (lstDocuments.Items.Count == 0)
            {
                MessageBox.Show("Os arquivos selecionados não são pacotes Open XML válidos.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
            this.Cursor = Cursors.Arrow;
            return(true);
        }
Exemple #13
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            lbl_height.Text     = $"{Blockchain.Default.Height}/{Blockchain.Default.HeaderHeight}";
            lbl_count_node.Text = Program.LocalNode.RemoteNodeCount.ToString();
            TimeSpan persistence_span = DateTime.Now - persistence_time;

            if (persistence_span > Blockchain.TimePerBlock)
            {
                toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
            }
            else
            {
                toolStripProgressBar1.Value = persistence_span.Seconds;
                toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
            }
            if (balance_changed)
            {
                IEnumerable <Coin> coins = Program.CurrentWallet?.FindCoins() ?? Enumerable.Empty <Coin>();
                var assets = coins.GroupBy(p => p.AssetId, (k, g) => new
                {
                    Asset     = (RegisterTransaction)Blockchain.Default.GetTransaction(k),
                    Value     = g.Sum(p => p.Value),
                    Available = g.Where(p => p.State == CoinState.Unspent).Sum(p => p.Value)
                }).ToDictionary(p => p.Asset.Hash);
                foreach (RegisterTransaction tx in listView2.Items.OfType <ListViewItem>().Select(p => (RegisterTransaction)p.Tag).ToArray())
                {
                    if (!assets.ContainsKey(tx.Hash))
                    {
                        listView2.Items.RemoveByKey(tx.Hash.ToString());
                    }
                }
                foreach (var asset in assets.Values)
                {
                    if (listView2.Items.ContainsKey(asset.Asset.Hash.ToString()))
                    {
                        listView2.Items[asset.Asset.Hash.ToString()].SubItems["value"].Text = asset.Value.ToString();
                    }
                    else
                    {
                        listView2.Items.Add(new ListViewItem(new[]
                        {
                            new ListViewItem.ListViewSubItem
                            {
                                Name = "name",
                                Text = asset.Asset.GetName()
                            },
                            new ListViewItem.ListViewSubItem
                            {
                                Name = "type",
                                Text = asset.Asset.AssetType.ToString()
                            },
                            new ListViewItem.ListViewSubItem
                            {
                                Name = "value",
                                Text = asset.Value.ToString()
                            },
                            new ListViewItem.ListViewSubItem
                            {
                                ForeColor = Color.Gray,
                                Name      = "issuer",
                                Text      = $"{Strings.UnknownIssuer}[{asset.Asset.Issuer}]"
                            }
                        }, -1, listView2.Groups["unchecked"])
                        {
                            Name = asset.Asset.Hash.ToString(),
                            Tag  = asset.Asset,
                            UseItemStyleForSubItems = false
                        });
                    }
                }
                balance_changed = false;
            }
            foreach (ListViewItem item in listView2.Groups["unchecked"].Items.OfType <ListViewItem>().ToArray())
            {
                ListViewItem.ListViewSubItem subitem = item.SubItems["issuer"];
                RegisterTransaction          asset   = (RegisterTransaction)item.Tag;
                byte[] cert_url_data = asset.Attributes.FirstOrDefault(p => p.Usage == TransactionAttributeUsage.CertUrl)?.Data;
                string cert_url      = cert_url_data == null ? null : Encoding.UTF8.GetString(cert_url_data);
                using (CertificateQueryResult result = CertificateQueryService.Query(asset.Issuer, cert_url))
                {
                    switch (result.Type)
                    {
                    case CertificateQueryResultType.Querying:
                    case CertificateQueryResultType.QueryFailed:
                        break;

                    case CertificateQueryResultType.System:
                        subitem.ForeColor = Color.Green;
                        subitem.Text      = Strings.SystemIssuer;
                        break;

                    case CertificateQueryResultType.Invalid:
                        subitem.ForeColor = Color.Red;
                        subitem.Text      = $"[{Strings.InvalidCertificate}][{asset.Issuer}]";
                        break;

                    case CertificateQueryResultType.Expired:
                        subitem.ForeColor = Color.Yellow;
                        subitem.Text      = $"[{Strings.ExpiredCertificate}]{result.Certificate.Subject}[{asset.Issuer}]";
                        break;

                    case CertificateQueryResultType.Good:
                        subitem.ForeColor = Color.Black;
                        subitem.Text      = $"{result.Certificate.Subject}[{asset.Issuer}]";
                        break;
                    }
                    switch (result.Type)
                    {
                    case CertificateQueryResultType.System:
                    case CertificateQueryResultType.Missing:
                    case CertificateQueryResultType.Invalid:
                    case CertificateQueryResultType.Expired:
                    case CertificateQueryResultType.Good:
                        item.Group = listView2.Groups["checked"];
                        break;
                    }
                }
            }
        }
Exemple #14
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            lbl_height.Text     = $"{Blockchain.Default.Height}/{Blockchain.Default.HeaderHeight}";
            lbl_count_node.Text = Program.LocalNode.RemoteNodeCount.ToString();
            TimeSpan persistence_span = DateTime.Now - persistence_time;

            if (persistence_span > Blockchain.TimePerBlock)
            {
                toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
            }
            else
            {
                toolStripProgressBar1.Value = persistence_span.Seconds;
                toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
            }
            if (Program.CurrentWallet?.WalletHeight > Blockchain.Default.Height + 1)
            {
                return;
            }
            if (balance_changed)
            {
                IEnumerable <Coin> coins             = Program.CurrentWallet?.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent)) ?? Enumerable.Empty <Coin>();
                Fixed8             bonus_available   = Blockchain.CalculateBonus(Program.CurrentWallet.GetUnclaimedCoins().Select(p => p.Reference));
                Fixed8             bonus_unavailable = Blockchain.CalculateBonus(coins.Where(p => p.State.HasFlag(CoinState.Confirmed) && p.Output.AssetId.Equals(Blockchain.SystemShare.Hash)).Select(p => p.Reference), Blockchain.Default.Height + 1);
                Fixed8             bonus             = bonus_available + bonus_unavailable;
                var assets = coins.GroupBy(p => p.Output.AssetId, (k, g) => new
                {
                    Asset = Blockchain.Default.GetAssetState(k),
                    Value = g.Sum(p => p.Output.Value),
                    Claim = k.Equals(Blockchain.SystemCoin.Hash) ? bonus : Fixed8.Zero
                }).ToDictionary(p => p.Asset.AssetId);
                if (bonus != Fixed8.Zero && !assets.ContainsKey(Blockchain.SystemCoin.Hash))
                {
                    assets[Blockchain.SystemCoin.Hash] = new
                    {
                        Asset = Blockchain.Default.GetAssetState(Blockchain.SystemCoin.Hash),
                        Value = Fixed8.Zero,
                        Claim = bonus
                    };
                }
                var balance_ans = coins.Where(p => p.Output.AssetId.Equals(Blockchain.SystemShare.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                var balance_anc = coins.Where(p => p.Output.AssetId.Equals(Blockchain.SystemCoin.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                foreach (ListViewItem item in listView1.Items)
                {
                    UInt160 script_hash = Wallet.ToScriptHash(item.Name);
                    Fixed8  ans         = balance_ans.ContainsKey(script_hash) ? balance_ans[script_hash] : Fixed8.Zero;
                    Fixed8  anc         = balance_anc.ContainsKey(script_hash) ? balance_anc[script_hash] : Fixed8.Zero;
                    item.SubItems["ans"].Text = ans.ToString();
                    item.SubItems["anc"].Text = anc.ToString();
                }
                foreach (AssetState asset in listView2.Items.OfType <ListViewItem>().Select(p => (AssetState)p.Tag).ToArray())
                {
                    if (!assets.ContainsKey(asset.AssetId))
                    {
                        listView2.Items.RemoveByKey(asset.AssetId.ToString());
                    }
                }
                foreach (var asset in assets.Values)
                {
                    string value_text = asset.Value.ToString() + (asset.Asset.AssetId.Equals(Blockchain.SystemCoin.Hash) ? $"+({asset.Claim})" : "");
                    if (listView2.Items.ContainsKey(asset.Asset.AssetId.ToString()))
                    {
                        listView2.Items[asset.Asset.AssetId.ToString()].SubItems["value"].Text = value_text;
                    }
                    else
                    {
                        listView2.Items.Add(new ListViewItem(new[]
                        {
                            new ListViewItem.ListViewSubItem
                            {
                                Name = "name",
                                Text = asset.Asset.GetName()
                            },
                            new ListViewItem.ListViewSubItem
                            {
                                Name = "type",
                                Text = asset.Asset.AssetType.ToString()
                            },
                            new ListViewItem.ListViewSubItem
                            {
                                Name = "value",
                                Text = value_text
                            },
                            new ListViewItem.ListViewSubItem
                            {
                                ForeColor = Color.Gray,
                                Name      = "issuer",
                                Text      = $"{Strings.UnknownIssuer}[{asset.Asset.Owner}]"
                            }
                        }, -1, listView2.Groups["unchecked"])
                        {
                            Name = asset.Asset.AssetId.ToString(),
                            Tag  = asset.Asset,
                            UseItemStyleForSubItems = false
                        });
                    }
                }
                balance_changed = false;
            }
            foreach (ListViewItem item in listView2.Groups["unchecked"].Items.OfType <ListViewItem>().ToArray())
            {
                ListViewItem.ListViewSubItem subitem = item.SubItems["issuer"];
                AssetState             asset         = (AssetState)item.Tag;
                CertificateQueryResult result;
                if (asset.AssetType == AssetType.SystemShare || asset.AssetType == AssetType.SystemCoin)
                {
                    result = new CertificateQueryResult {
                        Type = CertificateQueryResultType.System
                    };
                }
                else
                {
                    result = CertificateQueryService.Query(asset.Owner);
                }
                using (result)
                {
                    subitem.Tag = result.Type;
                    switch (result.Type)
                    {
                    case CertificateQueryResultType.Querying:
                    case CertificateQueryResultType.QueryFailed:
                        break;

                    case CertificateQueryResultType.System:
                        subitem.ForeColor = Color.Green;
                        subitem.Text      = Strings.SystemIssuer;
                        break;

                    case CertificateQueryResultType.Invalid:
                        subitem.ForeColor = Color.Red;
                        subitem.Text      = $"[{Strings.InvalidCertificate}][{asset.Owner}]";
                        break;

                    case CertificateQueryResultType.Expired:
                        subitem.ForeColor = Color.Yellow;
                        subitem.Text      = $"[{Strings.ExpiredCertificate}]{result.Certificate.Subject}[{asset.Owner}]";
                        break;

                    case CertificateQueryResultType.Good:
                        subitem.ForeColor = Color.Black;
                        subitem.Text      = $"{result.Certificate.Subject}[{asset.Owner}]";
                        break;
                    }
                    switch (result.Type)
                    {
                    case CertificateQueryResultType.System:
                    case CertificateQueryResultType.Missing:
                    case CertificateQueryResultType.Invalid:
                    case CertificateQueryResultType.Expired:
                    case CertificateQueryResultType.Good:
                        item.Group = listView2.Groups["checked"];
                        break;
                    }
                }
            }
        }
        private void LoadContracts()
        {
            int loans = 0;

            lvContracts.Items.Clear();

            PaymentMethod paymentMethod =
                ServicesProvider.GetInstance().GetPaymentMethodServices().GetPaymentMethodById(1);

            foreach (VillageMember member in _village.Members)
            {
                foreach (Loan loan in member.ActiveLoans)
                {
                    if (null == loan || loan.ContractStatus != OContractStatus.Active)
                    {
                        continue;
                    }
                    if (loan.NsgID != _village.Id)
                    {
                        continue;
                    }

                    var         result      = new KeyValuePair <Loan, RepaymentEvent>();
                    Installment installment = loan.GetFirstUnpaidInstallment();

                    if (null == installment)
                    {
                        continue;
                    }

                    loans++;

                    Person       person = member.Tiers as Person;
                    ListViewItem item   = new ListViewItem(person.Name)
                    {
                        Tag = loan
                    };
                    item.SubItems.Add(loan.Code);

                    OCurrency principalHasToPay = result.Value == null
                                                      ? installment.PrincipalHasToPay
                                                      : (result.Value).Principal;

                    ListViewItem.ListViewSubItem subitem = new ListViewItem.ListViewSubItem
                    {
                        Text = principalHasToPay.GetFormatedValue(
                            loan.UseCents),
                        Tag = principalHasToPay
                    };
                    item.SubItems.Add(subitem);

                    OCurrency interestHasToPay = result.Value == null
                                                      ? installment.InterestHasToPay
                                                      : (result.Value).Interests;

                    subitem = new ListViewItem.ListViewSubItem
                    {
                        Text = interestHasToPay.GetFormatedValue(loan.UseCents),
                        Tag  = interestHasToPay
                    };
                    item.SubItems.Add(subitem);

                    subitem = new ListViewItem.ListViewSubItem();
                    OCurrency penalties = loan.CalculateDuePenaltiesForInstallment(installment.Number,
                                                                                   TimeProvider.Today);
                    subitem.Text = penalties.GetFormatedValue(loan.UseCents);
                    subitem.Tag  = penalties;
                    item.SubItems.Add(subitem);

                    subitem = new ListViewItem.ListViewSubItem();
                    OCurrency total = principalHasToPay + interestHasToPay + penalties;
                    subitem.Text = total.GetFormatedValue(loan.UseCents);
                    subitem.Tag  = total;
                    item.SubItems.Add(subitem);

                    subitem = new ListViewItem.ListViewSubItem();
                    OCurrency olb = ServicesProvider.GetInstance().GetGeneralSettings().IsOlbBeforeRepayment
                                        ? installment.OLB
                                        : installment.OLBAfterRepayment;
                    subitem.Text = olb.GetFormatedValue(loan.UseCents);
                    subitem.Tag  = olb;
                    item.SubItems.Add(subitem);

                    OCurrency dueInterest = 0;
                    foreach (Installment installmentItem in loan.InstallmentList)
                    {
                        if (!installmentItem.IsRepaid)
                        {
                            dueInterest += installmentItem.InterestsRepayment - installmentItem.PaidInterests;
                        }
                    }

                    subitem = new ListViewItem.ListViewSubItem
                    {
                        Text = dueInterest.GetFormatedValue(loan.UseCents),
                        Tag  = dueInterest
                    };
                    item.SubItems.Add(subitem);

                    subitem = new ListViewItem.ListViewSubItem
                    {
                        Text = loan.Product.Currency.Code,
                        Tag  = loan.Product.Currency
                    };
                    item.SubItems.Add(subitem);

                    cbItem.SelectedIndex = 0;

                    subitem = new ListViewItem.ListViewSubItem
                    {
                        Text = cbItem.SelectedItem.ToString(),
                        Tag  = cbItem.SelectedItem
                    };
                    item.SubItems.Add(subitem);

                    subitem = new ListViewItem.ListViewSubItem();
                    item.SubItems.Add(subitem);

                    lvContracts.Items.Add(item);
                }
            }

            if (0 == loans)
            {
                btnOK.Enabled = false;
                return;
            }

            _itemTotal.SubItems.Add("");
            _itemTotal.SubItems.Add("0");
            _itemTotal.SubItems.Add("0");
            _itemTotal.SubItems.Add("0");
            _itemTotal.SubItems.Add("0");
            _itemTotal.SubItems.Add("");
            _itemTotal.SubItems.Add("");
            _itemTotal.SubItems.Add("");
            _itemTotal.SubItems.Add("");

            lvContracts.Items.Add(_itemTotal);
        }
Exemple #16
0
        public void ListViewSubItemConverter_ConvertTo_InstanceDescriptor_ReturnsExpected(ListViewItem.ListViewSubItem value, Type[] parameterTypes, object[] arguments)
        {
            TypeConverter      converter  = TypeDescriptor.GetConverter(typeof(ListViewItem.ListViewSubItem));
            InstanceDescriptor descriptor = Assert.IsType <InstanceDescriptor>(converter.ConvertTo(value, typeof(InstanceDescriptor)));

            Assert.Equal(typeof(ListViewItem.ListViewSubItem).GetConstructor(parameterTypes), descriptor.MemberInfo);
            Assert.Equal(arguments, descriptor.Arguments);
        }
Exemple #17
0
        private void InitializeControls()
        {
            lvMembers.Items.Clear();
            _fLServices.EmptyTemporaryFLAmountsStorage();
            ApplicationSettings dataParam = ApplicationSettings.GetInstance(string.Empty);
            int decimalPlaces             = dataParam.InterestRateDecimalPlaces;

            foreach (VillageMember member in _village.NonDisbursedMembers)
            {
                foreach (Loan loan in member.ActiveLoans)
                {
                    if (loan.ContractStatus == OContractStatus.Active ||
                        loan.ContractStatus == OContractStatus.Refused ||
                        loan.ContractStatus == OContractStatus.Abandoned
                        )
                    {
                        continue;
                    }
                    _hasMember = true;
                    Person       person = member.Tiers as Person;
                    ListViewItem item   = new ListViewItem(person.Name)
                    {
                        Tag = loan
                    };
                    item.UseItemStyleForSubItems = true;
                    item.SubItems.Add(person.IdentificationData);
                    ListViewItem.ListViewSubItem subitem = new ListViewItem.ListViewSubItem
                    {
                        Text = TimeProvider.Today.ToShortDateString(),
                        Tag  = TimeProvider.Today
                    };
                    item.SubItems.Add(subitem);
                    item.SubItems.Add(loan.FirstInstallmentDate.ToShortDateString());
                    item.SubItems.Add(loan.Amount.GetFormatedValue(loan.UseCents));
                    item.SubItems.Add(loan.Product.Currency.Code);
                    item.SubItems.Add(Math.Round(loan.InterestRate * 100, decimalPlaces).ToString());
                    item.SubItems.Add(loan.GracePeriod.ToString());
                    item.SubItems.Add(loan.NbOfInstallments.ToString());
                    item.SubItems.Add(loan.LoanOfficer.Name);
                    item.SubItems.Add(loan.FundingLine.Name);

                    _accumulatedAmount = _fLServices.CheckIfAmountIsEnough(loan.FundingLine, loan.Amount.Value);
                    if (_accumulatedAmount <= 0)
                    {
                        item.BackColor = Color.Red;
                    }
                    item.SubItems.Add(_accumulatedAmount.ToString());

                    cbPaymentMethods.Items.Clear();
                    List <PaymentMethod> methods = ServicesProvider.GetInstance().GetPaymentMethodServices().GetAllPaymentMethods();
                    item.SubItems.Add(methods[0].Name);

                    lvMembers.Items.Add(item);
                    item.SubItems[IdxAmount].Tag   = loan.Amount.GetFormatedValue(loan.UseCents);
                    item.SubItems[IdxCurrency].Tag = loan.Product.Currency;
                }
            }

            if (_hasMember)
            {
                OCurrency zero = 0m;
                _itemTotal.Text = GetString("total");
                _itemTotal.SubItems.Add("");
                _itemTotal.SubItems.Add("");
                _itemTotal.SubItems.Add("");
                _itemTotal.SubItems.Add(zero.GetFormatedValue(true));
                _itemTotal.SubItems.Add("");
                lvMembers.Items.Add(_itemTotal);
            }

            lvMembers.SubItemClicked       += lvMembers_SubItemClicked;
            lvMembers.DoubleClickActivation = true;
        }
Exemple #18
0
        public static IEnumerable <object[]> ConvertTo_InstanceDescriptor_TestData()
        {
            var group    = new ListViewGroup();
            var subItem1 = new ListViewItem.ListViewSubItem(null, "text1");
            var subItem2 = new ListViewItem.ListViewSubItem(null, "text2");
            var subItem3 = new ListViewItem.ListViewSubItem(null, "text3")
            {
                ForeColor = Color.Blue
            };
            var subItem4 = new ListViewItem.ListViewSubItem(null, "text4")
            {
                BackColor = Color.Blue
            };
            var subItem5 = new ListViewItem.ListViewSubItem(null, "text5")
            {
                Font = SystemFonts.MenuFont
            };

            // Simple.
            yield return(new object[]
            {
                new ListViewItem(),
                new Type[] { typeof(string) },
                new object[] { string.Empty }
            });

            yield return(new object[]
            {
                new ListViewItem(group),
                new Type[] { typeof(string) },
                new object[] { string.Empty }
            });

            yield return(new object[]
            {
                new ListViewItem("text"),
                new Type[] { typeof(string) },
                new object[] { "text" }
            });

            yield return(new object[]
            {
                new ListViewItem("text", group),
                new Type[] { typeof(string) },
                new object[] { "text" }
            });

            yield return(new object[]
            {
                new ListViewItem("text", "imageKey"),
                new Type[] { typeof(string), typeof(string) },
                new object[] { "text", "imageKey" }
            });

            yield return(new object[]
            {
                new ListViewItem("text", 1),
                new Type[] { typeof(string), typeof(int) },
                new object[] { "text", 1 }
            });

            yield return(new object[]
            {
                new ListViewItem("text", "imageKey", group),
                new Type[] { typeof(string), typeof(string) },
                new object[] { "text", "imageKey" }
            });

            yield return(new object[]
            {
                new ListViewItem("text", 1, group),
                new Type[] { typeof(string), typeof(int) },
                new object[] { "text", 1 }
            });

            // Item.
            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1 }, "imageKey"),
                new Type[] { typeof(string), typeof(string) },
                new object[] { "text1", "imageKey" }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1 }, 1),
                new Type[] { typeof(string), typeof(int) },
                new object[] { "text1", 1 }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1 }, "imageKey", group),
                new Type[] { typeof(string), typeof(string) },
                new object[] { "text1", "imageKey" }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1 }, 1, group),
                new Type[] { typeof(string), typeof(int) },
                new object[] { "text1", 1 }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1, subItem2 }, "imageKey"),
                new Type[] { typeof(string[]), typeof(string) },
                new object[] { new string[] { "text1", "text2" }, "imageKey" }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1, subItem2 }, 1),
                new Type[] { typeof(string[]), typeof(int) },
                new object[] { new string[] { "text1", "text2" }, 1 }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1, subItem2 }, "imageKey", group),
                new Type[] { typeof(string[]), typeof(string) },
                new object[] { new string[] { "text1", "text2" }, "imageKey" }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1, subItem2 }, 1, group),
                new Type[] { typeof(string[]), typeof(int) },
                new object[] { new string[] { "text1", "text2" }, 1 }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1, subItem2, subItem3, subItem4, subItem5 }, "imageKey"),
                new Type[] { typeof(ListViewItem.ListViewSubItem[]), typeof(string) },
                new object[] { new ListViewItem.ListViewSubItem[] { subItem1, subItem2, subItem3, subItem4, subItem5 }, "imageKey" }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1, subItem2, subItem3, subItem4, subItem5 }, 1),
                new Type[] { typeof(ListViewItem.ListViewSubItem[]), typeof(int) },
                new object[] { new ListViewItem.ListViewSubItem[] { subItem1, subItem2, subItem3, subItem4, subItem5 }, 1 }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1, subItem2, subItem3, subItem4, subItem5 }, "imageKey", group),
                new Type[] { typeof(ListViewItem.ListViewSubItem[]), typeof(string) },
                new object[] { new ListViewItem.ListViewSubItem[] { subItem1, subItem2, subItem3, subItem4, subItem5 }, "imageKey" }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem1, subItem2, subItem3, subItem4, subItem5 }, 1, group),
                new Type[] { typeof(ListViewItem.ListViewSubItem[]), typeof(int) },
                new object[] { new ListViewItem.ListViewSubItem[] { subItem1, subItem2, subItem3, subItem4, subItem5 }, 1 }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem3 }, 1),
                new Type[] { typeof(string[]), typeof(int), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text3" }, 1, Color.Blue, Color.Empty, null }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem4 }, 1),
                new Type[] { typeof(string[]), typeof(int), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text4" }, 1, Color.Empty, Color.Blue, null }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem5 }, 1),
                new Type[] { typeof(string[]), typeof(int), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text5" }, 1, Color.Empty, Color.Empty, SystemFonts.MenuFont }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem3 }, "imageKey"),
                new Type[] { typeof(string[]), typeof(string), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text3" }, "imageKey", Color.Blue, Color.Empty, null }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem4 }, "imageKey"),
                new Type[] { typeof(string[]), typeof(string), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text4" }, "imageKey", Color.Empty, Color.Blue, null }
            });

            yield return(new object[]
            {
                new ListViewItem(new ListViewItem.ListViewSubItem[] { subItem5 }, "imageKey"),
                new Type[] { typeof(string[]), typeof(string), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text5" }, "imageKey", Color.Empty, Color.Empty, SystemFonts.MenuFont }
            });

            // Custom style - text.
            yield return(new object[]
            {
                new ListViewItem(new string[] { "text" }, "imageKey", Color.Red, Color.Blue, SystemFonts.MenuFont),
                new Type[] { typeof(string[]), typeof(string), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text" }, "imageKey", Color.Red, Color.Blue, SystemFonts.MenuFont }
            });

            yield return(new object[]
            {
                new ListViewItem(new string[] { "text" }, 1, Color.Red, Color.Blue, SystemFonts.MenuFont),
                new Type[] { typeof(string[]), typeof(int), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text" }, 1, Color.Red, Color.Blue, SystemFonts.MenuFont }
            });

            yield return(new object[]
            {
                new ListViewItem(new string[] { "text" }, "imageKey", Color.Red, Color.Blue, SystemFonts.MenuFont, group),
                new Type[] { typeof(string[]), typeof(string), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text" }, "imageKey", Color.Red, Color.Blue, SystemFonts.MenuFont }
            });

            yield return(new object[]
            {
                new ListViewItem(new string[] { "text" }, 1, Color.Red, Color.Blue, SystemFonts.MenuFont, group),
                new Type[] { typeof(string[]), typeof(int), typeof(Color), typeof(Color), typeof(Font) },
                new object[] { new string[] { "text" }, 1, Color.Red, Color.Blue, SystemFonts.MenuFont }
            });
        }
Exemple #19
0
        // Carrega a lista de Filmes //



        private void MetodoConsulta()
        {
            try
            {
                CONEXAO.Open();

                SqlCommand CONSULTAFILME;

                if (radioButton_Cod_Filme.Checked == true)
                {
                    CONSULTAFILME = new SqlCommand("SELECT CODFILMES.COD_Cod, FILMES.FIL_Titulo, GENEROS.GEN_Desc, FILMES.FIL_Classificacao, CATALOGO_PRECOS.CAT_DESCRICAO, TIPOS_MIDIAS.TIP_Desc, CODFILMES.COD_Status FROM CODFILMES INNER JOIN FILMES ON CODFILMES.FIL_Cod = FILMES.FIL_Cod INNER JOIN GENEROS ON FILMES.GEN_Cod = GENEROS.GEN_Cod INNER JOIN CATALOGO_PRECOS ON FILMES.CAT_Cod = CATALOGO_PRECOS.CAT_Cod INNER JOIN TIPOS_MIDIAS ON CODFILMES.TIP_Cod = TIPOS_MIDIAS.TIP_Cod WHERE CODFILMES.COD_Cod = @COD_FIL;", CONEXAO);
                    SqlParameter CF1 = new SqlParameter("@COD_FIL", int.Parse(maskedTextBox_Cod_Filme.Text));
                    CONSULTAFILME.Parameters.Add(CF1);
                }
                else
                {
                    CONSULTAFILME = new SqlCommand("SELECT CODFILMES.COD_Cod, FILMES.FIL_Titulo, GENEROS.GEN_Desc, FILMES.FIL_Classificacao, CATALOGO_PRECOS.CAT_DESCRICAO, TIPOS_MIDIAS.TIP_Desc, CODFILMES.COD_Status FROM CODFILMES INNER JOIN FILMES ON CODFILMES.FIL_Cod = FILMES.FIL_Cod INNER JOIN GENEROS ON FILMES.GEN_Cod = GENEROS.GEN_Cod INNER JOIN CATALOGO_PRECOS ON FILMES.CAT_Cod = CATALOGO_PRECOS.CAT_Cod INNER JOIN TIPOS_MIDIAS ON CODFILMES.TIP_Cod = TIPOS_MIDIAS.TIP_Cod WHERE FILMES.FIL_TITULO like @NOME_FIL ORDER BY FILMES.FIL_TITULO", CONEXAO);
                    SqlParameter CF1 = new SqlParameter("@NOME_FIL", "%" + textBox_Nome_Filme.Text + "%");
                    CONSULTAFILME.Parameters.Add(CF1);
                }


                LEITOR = null;
                LEITOR = CONSULTAFILME.ExecuteReader();

                listView_Filmes_Disponiveis.Items.Clear();

                while (LEITOR.Read())
                {
                    ListViewItem CODIGO_FILMES = new ListViewItem(LEITOR["COD_Cod"].ToString());

                    ListViewItem.ListViewSubItem TITULO_FILME = new ListViewItem.ListViewSubItem();

                    ListViewItem.ListViewSubItem GENERO_FILME = new ListViewItem.ListViewSubItem();

                    ListViewItem.ListViewSubItem CLASSIFICACAO_FILME = new ListViewItem.ListViewSubItem();

                    ListViewItem.ListViewSubItem TIPO_MIDIA = new ListViewItem.ListViewSubItem();

                    ListViewItem.ListViewSubItem CATALOGO_PRECO_FILME = new ListViewItem.ListViewSubItem();

                    ListViewItem.ListViewSubItem STATUS_FILME = new ListViewItem.ListViewSubItem();


                    TITULO_FILME.Text = LEITOR["FIL_Titulo"].ToString();
                    CODIGO_FILMES.SubItems.Add(TITULO_FILME);

                    GENERO_FILME.Text = LEITOR["GEN_Desc"].ToString();
                    CODIGO_FILMES.SubItems.Add(GENERO_FILME);

                    CLASSIFICACAO_FILME.Text = LEITOR["FIL_Classificacao"].ToString();
                    CODIGO_FILMES.SubItems.Add(CLASSIFICACAO_FILME);

                    TIPO_MIDIA.Text = LEITOR["TIP_Desc"].ToString();
                    CODIGO_FILMES.SubItems.Add(TIPO_MIDIA);

                    CATALOGO_PRECO_FILME.Text = LEITOR["CAT_Descricao"].ToString();
                    CODIGO_FILMES.SubItems.Add(CATALOGO_PRECO_FILME);

                    if (LEITOR["COD_Status"].ToString() == "0")
                    {
                        STATUS_FILME.Text = "DISPONÍVEL";
                    }
                    else
                    {
                        STATUS_FILME.Text = "LOCADO";
                    }

                    CODIGO_FILMES.SubItems.Add(STATUS_FILME);

                    listView_Filmes_Disponiveis.Items.Add(CODIGO_FILMES);
                }
            }
            catch
            {
                MessageBox.Show("Houve um problema ao carregar os FILMES", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (LEITOR != null)
                {
                    LEITOR.Close();
                }

                if (CONEXAO != null && CONEXAO.State == ConnectionState.Open)
                {
                    CONEXAO.Close();
                }
            }
        }
        public void ListViewHitTestInfo_Ctor_ListViewItem_ListViewSubItem_ListViewHitTestLocations(ListViewItem hitItem, ListViewItem.ListViewSubItem hitSubItem, ListViewHitTestLocations hitTestLocations)
        {
            var info = new ListViewHitTestInfo(hitItem, hitSubItem, hitTestLocations);

            Assert.Equal(hitItem, info.Item);
            Assert.Equal(hitSubItem, info.SubItem);
            Assert.Equal(hitTestLocations, info.Location);
        }
        public void updateViewList() // funchtion for get values from xml to view list
        {
            // Adding columns for list view

            listViewHistory.Columns.Add(" ", 87, HorizontalAlignment.Center);                     // sub item 0
            listViewHistory.Columns.Add("Customer Name", 170, HorizontalAlignment.Left);          //  sub item 1
            listViewHistory.Columns.Add("Medicine Name", 150, HorizontalAlignment.Center);        // sub item 2
            listViewHistory.Columns.Add("Mg", 70, HorizontalAlignment.Center);                    // sub item 3
            listViewHistory.Columns.Add("Medicine Sold Amount", 150, HorizontalAlignment.Center); // sub item 4
            listViewHistory.Columns.Add("Total Price", 150, HorizontalAlignment.Center);          // sub item 4
            listViewHistory.Columns.Add("Recipe", 150, HorizontalAlignment.Center);
            listViewHistory.Columns.Add("Sell Date", 150, HorizontalAlignment.Center);

            //----------------------------------------------------------------------------

            // getting elements in xml to the temperory list. Each tag have its own list.
            XmlDocument history = new XmlDocument();

            history.Load(historyXmlFileLocation);

            XmlNodeList customerNameList = history.GetElementsByTagName("customerName");
            XmlNodeList medicineNameList = history.GetElementsByTagName("medicineName");
            XmlNodeList amountList       = history.GetElementsByTagName("amount");
            XmlNodeList recipeList       = history.GetElementsByTagName("recipe");
            XmlNodeList totalPriceList   = history.GetElementsByTagName("totalPrice");
            XmlNodeList mgList           = history.GetElementsByTagName("mg");
            XmlNodeList sellDateList     = history.GetElementsByTagName("sellDate");


            //--------------------------------------------------------------------------------------


            for (int i = 0; i < customerNameList.Count; i++)// Assıgning every element from xml document to developer defined medicineRecords class list
            {
                customerRecordsList.Add(new customerRecords
                {
                    customerName = customerNameList[i].InnerXml,
                    medicineName = medicineNameList[i].InnerXml,
                    mg           = XmlConvert.ToDouble(mgList[i].InnerXml),
                    amount       = int.Parse(amountList[i].InnerXml),
                    recipe       = recipeList[i].InnerXml,
                    totalPrice   = XmlConvert.ToDouble(totalPriceList[i].InnerXml),
                    sellDate     = sellDateList[i].InnerXml,
                });
            }


            for (var i = 0; i < customerRecordsList.Count; i++)// Adding medicineRecors list's elements to the list view
            {
                ListViewItem row = new ListViewItem((i + 1).ToString());

                ListViewItem.ListViewSubItem itms1 = new ListViewItem.ListViewSubItem(row, customerRecordsList[i].customerName.ToString());
                ListViewItem.ListViewSubItem itms8 = new ListViewItem.ListViewSubItem(row, customerRecordsList[i].medicineName.ToString());
                ListViewItem.ListViewSubItem itms2 = new ListViewItem.ListViewSubItem(row, customerRecordsList[i].mg.ToString());
                ListViewItem.ListViewSubItem itms3 = new ListViewItem.ListViewSubItem(row, customerRecordsList[i].amount.ToString());
                ListViewItem.ListViewSubItem itms4 = new ListViewItem.ListViewSubItem(row, customerRecordsList[i].totalPrice.ToString());
                ListViewItem.ListViewSubItem itms5 = new ListViewItem.ListViewSubItem(row, customerRecordsList[i].recipe.ToString());
                ListViewItem.ListViewSubItem itms6 = new ListViewItem.ListViewSubItem(row, customerRecordsList[i].sellDate.ToString());



                row.ImageIndex = i;
                row.SubItems.Add(itms1);
                row.SubItems.Add(itms8);
                row.SubItems.Add(itms2);
                row.SubItems.Add(itms3);
                row.SubItems.Add(itms4);
                row.SubItems.Add(itms5);
                row.SubItems.Add(itms6);

                listViewHistory.Items.Add(row);
            }
        }
Exemple #22
0
        private void Add(Paragraph paragraph)
        {
            var item = new ListViewItem(paragraph.Number.ToString(CultureInfo.InvariantCulture))
            {
                Tag = paragraph
            };

            ListViewItem.ListViewSubItem subItem;

            if (Configuration.Settings != null && Configuration.Settings.General.UseTimeFormatHHMMSSFF)
            {
                if (paragraph.StartTime.IsMaxTime)
                {
                    subItem = new ListViewItem.ListViewSubItem(item, "-");
                }
                else
                {
                    subItem = new ListViewItem.ListViewSubItem(item, paragraph.StartTime.ToHHMMSSFF());
                }
                item.SubItems.Add(subItem);

                if (paragraph.EndTime.IsMaxTime)
                {
                    subItem = new ListViewItem.ListViewSubItem(item, "-");
                }
                else
                {
                    subItem = new ListViewItem.ListViewSubItem(item, paragraph.EndTime.ToHHMMSSFF());
                }
                item.SubItems.Add(subItem);

                subItem = new ListViewItem.ListViewSubItem(item, string.Format("{0},{1:00}", paragraph.Duration.Seconds, Logic.SubtitleFormats.SubtitleFormat.MillisecondsToFramesMaxFrameRate(paragraph.Duration.Milliseconds)));
                item.SubItems.Add(subItem);
            }
            else
            {
                if (paragraph.StartTime.IsMaxTime)
                {
                    subItem = new ListViewItem.ListViewSubItem(item, "-");
                }
                else
                {
                    subItem = new ListViewItem.ListViewSubItem(item, paragraph.StartTime.ToString());
                }
                item.SubItems.Add(subItem);

                if (paragraph.EndTime.IsMaxTime)
                {
                    subItem = new ListViewItem.ListViewSubItem(item, "-");
                }
                else
                {
                    subItem = new ListViewItem.ListViewSubItem(item, paragraph.EndTime.ToString());
                }
                item.SubItems.Add(subItem);

                subItem = new ListViewItem.ListViewSubItem(item, string.Format("{0},{1:000}", paragraph.Duration.Seconds, paragraph.Duration.Milliseconds));
                item.SubItems.Add(subItem);
            }

            subItem = new ListViewItem.ListViewSubItem(item, paragraph.Text.Replace(Environment.NewLine, _lineSeparatorString));
            if (SubtitleFontBold)
            {
                subItem.Font = new Font(_subtitleFontName, SubtitleFontSize, FontStyle.Bold);
            }
            else
            {
                subItem.Font = new Font(_subtitleFontName, SubtitleFontSize);
            }

            item.UseItemStyleForSubItems = false;
            item.SubItems.Add(subItem);

            Items.Add(item);
        }
Exemple #23
0
        private void OpenDirectory(DirectoryInfo directory, bool searchMode = false, string filename = null)
        {
            infoText.Text = "Loading Directory..";
            fileListView.Items.Clear();
            ListViewItem.ListViewSubItem[] subItems;
            ListViewItem item = null;

            if (!directory.Exists)
            {
                MessageBox.Show("Could not find directory! Returning to original path..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                OpenDirectory(originalPath, false);
                return;
            }

            foreach (DirectoryInfo dir in directory.GetDirectories())
            {
                if (searchMode && !string.IsNullOrEmpty(filename))
                {
                    if (!dir.Name.Contains(filename))
                    {
                        continue;
                    }
                }
                item     = new ListViewItem(dir.Name, 0);
                item.Tag = dir;
                subItems = new ListViewItem.ListViewSubItem[]
                {
                    new ListViewItem.ListViewSubItem(item, "Directory"),
                    new ListViewItem.ListViewSubItem(item, (dir.GetDirectories().Length + dir.GetFiles().Length).ToString() + " items"),
                    new ListViewItem.ListViewSubItem(item, dir.LastWriteTime.ToShortDateString()),
                };
                item.SubItems.AddRange(subItems);
                fileListView.Items.Add(item);
            }

            foreach (FileInfo file in directory.GetFiles())
            {
                if (!imageBank.Images.ContainsKey(file.Extension))
                {
                    imageBank.Images.Add(file.Extension, Icon.ExtractAssociatedIcon(file.FullName));
                }

                //Icon.ExtractAssociatedIcon(file.FullName).ToBitmap().Save(file.Name + ".bmp");

                if (searchMode && !string.IsNullOrEmpty(filename))
                {
                    if (!file.Name.Contains(filename))
                    {
                        continue;
                    }
                }

                item     = new ListViewItem(file.Name, imageBank.Images.IndexOfKey(file.Extension));
                item.Tag = file;
                subItems = new ListViewItem.ListViewSubItem[]
                {
                    new ListViewItem.ListViewSubItem(item, DetermineFileType(file.Extension)),
                    new ListViewItem.ListViewSubItem(item, file.CalculateFileSize()),
                    new ListViewItem.ListViewSubItem(item, file.LastWriteTime.ToShortDateString()),
                };

                item.SubItems.AddRange(subItems);
                fileListView.Items.Add(item);
            }

            infoText.Text   = "Done loading directory.";
            FolderPath.Text = directory.FullName.Remove(0, directory.FullName.IndexOf(originalPath.Name));
            fileListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

            //sort out treeview stuff.
            currentDirectory = directory;
            string directoryPath = directory.FullName.Remove(0, directory.FullName.IndexOf(originalPath.Name)).TrimEnd('\\');

            //god this is terrible but it works.
            folderView.AfterExpand -= FolderViewAfterExpand;
            TreeNode nodeToExpand = folderView.Nodes.FindTreeNodeByFullPath(directoryPath);

            if (nodeToExpand != null)
            {
                nodeToExpand.Expand();
            }
            folderView.AfterExpand += FolderViewAfterExpand;
        }
Exemple #24
0
        private void backgroundWorkerPopulate_DoWork(object sender, DoWorkEventArgs e)
        {
            addLVI        addListViewItemDelegate = AddListViewItem;
            setDetailText setDetailTextDelegate   = SetDetailText;

            /* Full path */
            var fullPath      = new ListViewItem("Location");
            var fullPathValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.ParentDirectoryPath
            };

            fullPath.SubItems.Add(fullPathValue);
            fullPath.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { fullPath });

            /* Windows extension */
            var windowsExtension      = new ListViewItem("Indicated Extension");
            var windowsExtensionValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.Extension.Name
            };

            windowsExtension.SubItems.Add(windowsExtensionValue);
            windowsExtension.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { windowsExtension });

            /* Detected extension */
            var detectedExtension      = new ListViewItem("Detected Extension");
            var detectedExtensionValue = new ListViewItem.ListViewSubItem
            {
                Text = MimeGuesser.GuessExtension(fileItem.AbsolutePath)
            };

            detectedExtension.SubItems.Add(detectedExtensionValue);
            detectedExtension.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { detectedExtension });

            /* MIME Type */
            var mimeType      = new ListViewItem("Detected MIME Type");
            var mimeTypeValue = new ListViewItem.ListViewSubItem
            {
                Text = MimeGuesser.GuessMimeType(fileItem.AbsolutePath)
            };

            mimeType.SubItems.Add(mimeTypeValue);
            mimeType.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { mimeType });

            /* MIME Details */
            var    builder = new StringBuilder();
            string details = detailMagic.Read(fileItem.AbsolutePath);

            details = details.Replace("- data", string.Empty);

            foreach (var component in details.Split(','))
            {
                if (!component.Equals("- data"))
                {
                    builder.AppendLine(component.Trim());
                }
            }

            BeginInvoke(setDetailTextDelegate, new object[] { builder.ToString() });

            /* Size */
            var size      = new ListViewItem("Size");
            var sizeValue = new ListViewItem.ListViewSubItem
            {
                Text = Utils.GetDynamicFileSize(fileItem.AbsolutePath)
            };

            size.SubItems.Add(sizeValue);
            size.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { size });

            /* Creation date + time */
            var creationDateTime      = new ListViewItem("Creation Date");
            var creationDateTimeValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.CreationTimeAsText
            };

            creationDateTime.SubItems.Add(creationDateTimeValue);
            creationDateTime.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { creationDateTime });

            /* Access date + time */
            var accessDateTime      = new ListViewItem("Last Access Date");
            var accessDateTimeValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.LastAccessTimeAsText
            };

            accessDateTime.SubItems.Add(accessDateTimeValue);
            accessDateTime.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { accessDateTime });

            /* Modify date + time */
            var modifiedDateTime      = new ListViewItem("Last Modification Date");
            var modifiedDateTimeValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.LastWriteTimeAsText
            };

            modifiedDateTime.SubItems.Add(modifiedDateTimeValue);
            modifiedDateTime.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { modifiedDateTime });

            /* Attributes */
            var attributes      = new ListViewItem("Windows Attributes");
            var attributesValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.AttributesAsText
            };

            attributes.SubItems.Add(attributesValue);
            attributes.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { attributes });

            /* Owner */
            var owner      = new ListViewItem("Owner");
            var ownerValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.Owner
            };

            owner.SubItems.Add(ownerValue);
            owner.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { owner });
        }
        protected override void UpdateValue(object newValue)
        {
            if (this.ConverterInstance != null)
            {
                if (!dataLoaded)
                {
                    //selected items??
                    List <string> selectedStrings = new List <string>();
                    if (newValue != null)
                    {
                        if (newValue.GetType() == typeof(string))
                        {
                            if (!string.IsNullOrEmpty(newValue.ToString()))
                            {
                                string strValue = newValue.ToString();
                                if (strValue.Contains(";"))
                                {
                                    char[] sep = new char[] { ';' };
                                    foreach (string strSep in strValue.Split(sep))
                                    {
                                        if (strSep != "")
                                        {
                                            selectedStrings.Add(strSep);
                                        }
                                    }
                                }
                                else
                                {
                                    //nur 1 element drin
                                    selectedStrings.Add(strValue);
                                }
                            }
                        }
                    }

                    dataLoaded = true;
                    RuntimeServiceProvider serviceProvider = new RuntimeServiceProvider(this);
                    foreach (object o in this.ConverterInstance.GetStandardValues(serviceProvider))
                    {
                        if (o is NameValueItem)
                        {
                            NameValueItem nvi = o as NameValueItem;
                            ListViewItem  lvi = new ListViewItem(nvi.Name);
                            lvi.Tag      = nvi;
                            lvi.ImageKey = nvi.ItemType;
                            listview.Items.Add(lvi);

                            ListViewItem.ListViewSubItem slvi = new ListViewItem.ListViewSubItem();
                            slvi.Text = nvi.Description;
                            lvi.SubItems.Add(slvi);

                            if (ConverterInstance != null)
                            {
                                if (!ConverterInstance.IsValid(serviceProvider, nvi))
                                {
                                    lvi.ForeColor = Color.Gray;
                                }

                                //select a default value, if only one selection is allowed
                                if ((selectedStrings.Count == 0) && !withCheckboxes)
                                {
                                    if (listview.SelectedItems.Count == 0)
                                    {
                                        //ITypeDescriptorContext context = serviceProvider.GetService(typeof(ITypeDescriptorContext)) as ITypeDescriptorContext;

                                        if (ConverterInstance.IsValid(serviceProvider, nvi))
                                        {
                                            lvi.Selected = true;
                                        }
                                    }
                                }
                            }

                            if (selectedStrings.Contains(nvi.ToString()))
                            {
                                if (withCheckboxes)
                                {
                                    lvi.Checked = true;
                                }
                                else
                                {
                                    lvi.Selected = true;
                                }
                            }
                        }
                        else
                        {
                            NameValueItem nvi = new NameValueItem();
                            nvi.Name  = o.ToString();
                            nvi.Value = o.ToString();

                            ListViewItem lvi = new ListViewItem(o.ToString());
                            lvi.Tag      = nvi;
                            lvi.ImageKey = o.ToString();
                            listview.Items.Add(lvi);

                            if (selectedStrings.Contains(nvi.ToString()))
                            {
                                if (withCheckboxes)
                                {
                                    lvi.Checked = true;
                                }
                                else
                                {
                                    lvi.Selected = true;
                                }
                            }
                        }
                    }

                    //if only one item is available, go to the next wizard page, if there is only 1 visible control on the wizard page
                    if (listview.Items.Count == 1)
                    {
                        int controlcount = 0;
                        foreach (Control control in this.WizardPage.Controls)
                        {
                            if (control.Visible)
                            {
                                if (control.GetType() == typeof(Panel))
                                {
                                    //ignore the button panel
                                }
                                else
                                {
                                    controlcount++;
                                }
                            }
                        }
                        if (controlcount == 1)
                        {
                            //I'm the only one control on the wizard page
                            if (this.WizardPage.Wizard.NextPage != null)
                            {
                                this.WizardPage.Wizard.OnNext();

                                //this.WizardPage.Wizard.GotoPage(this.WizardPage.Wizard.NextPageFromPage(this.WizardPage));
                            }
                        }
                    }
                }
            }

            base.SetValue(newValue);
        }
 public ListViewColumnMouseEventArgs(MouseEventArgs e, ListViewItem item, ListViewItem.ListViewSubItem subItem)
     : base(e.Button, e.Clicks, e.X, e.Y, e.Delta)
 {
     Item    = item;
     SubItem = subItem;
 }
        protected override void OnDragDrop(DragEventArgs drgevent)
        {
            // get the currently hovered row that the items will be dragged to
            Point        clientPoint = base.PointToClient(new Point(drgevent.X, drgevent.Y));
            ListViewItem hoverItem   = base.GetItemAt(clientPoint.X, clientPoint.Y);

            if (!drgevent.Data.GetDataPresent(DataFormats.Text) || (string)drgevent.Data.GetData(DataFormats.Text) == "")
            {
                return;
            }

            bool   localSource = true;
            string controlName = "";
            string rawXml      = "";
            List <ListViewItem> insertItems = new List <ListViewItem>();

            //check if dragged object is from local listview
            if (drgevent.Data.GetType().ToString() == "System.__ComObject")
            {
                localSource = false;
                //return;
            }
            rawXml = (string)drgevent.Data.GetData("Text");
            if (rawXml.StartsWith("<"))
            {
                System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
                xdoc.LoadXml(rawXml);
                if (xdoc.DocumentElement.Name == this.Name)
                {
                    controlName = this.Name;
                    foreach (System.Xml.XmlElement xElem in xdoc.DocumentElement.ChildNodes)
                    {
                        if (xElem.Name == "listItem")
                        {
                            ListViewItem newItem = new ListViewItem(xElem.GetAttribute("columnText0"));
                            newItem.Checked    = bool.Parse(xElem.GetAttribute("checked"));
                            newItem.ImageIndex = int.Parse(xElem.GetAttribute("imageIndex"));
                            newItem.UseItemStyleForSubItems = bool.Parse(xElem.GetAttribute("useItemStyleForSubItems"));
                            string tagTypeStr = xElem.GetAttribute("tagType");
                            if (tagTypeStr.Length > 0)
                            {
                                Type   t         = Type.GetType(tagTypeStr);
                                object tagObject = QPerfMon.SerializationUtils.DeserializeXML(t, xElem.GetAttribute("tag"));
                                newItem.Tag = tagObject;
                            }
                            int columnCount = int.Parse(xElem.GetAttribute("columnCount"));
                            for (int i = 1; i < columnCount; i++)
                            {
                                ListViewItem.ListViewSubItem lsub = newItem.SubItems.Add(xElem.GetAttribute("columnText" + i.ToString()));
                                if (!newItem.UseItemStyleForSubItems)
                                {
                                    try
                                    {
                                        lsub.ForeColor = Color.FromArgb(int.Parse(xElem.GetAttribute("columnForeColor" + i.ToString())));
                                        lsub.BackColor = Color.FromArgb(int.Parse(xElem.GetAttribute("columnBackColor" + i.ToString())));
                                    }
                                    catch { }
                                }
                            }
                            insertItems.Add(newItem);
                        }
                    }
                }
                else
                {
                    return;
                }
            }
            else if (localSource) //Old format - only allowed when local
            {
                string[] draggedItems = ((string)drgevent.Data.GetData("Text")).Split('\x0');
                foreach (string draggedItem in draggedItems)
                {
                    string[] data = draggedItem.Split('\x1');
                    controlName = data[0];
                    int      itemIndex = int.Parse(data[1]);
                    string[] subItems  = new string[this.Columns.Count];
                    for (int i = 0; i < subItems.Length; i++)
                    {
                        subItems[i] = this.Items[itemIndex].SubItems[i].Text;
                    }
                    ListViewItem newItem = new ListViewItem(subItems);
                    newItem.Checked    = this.Items[itemIndex].Checked;
                    newItem.ImageIndex = this.Items[itemIndex].ImageIndex;
                    newItem.Tag        = this.Items[itemIndex].Tag;
                    newItem.UseItemStyleForSubItems = this.Items[itemIndex].UseItemStyleForSubItems;
                    for (int i = 1; i < newItem.SubItems.Count; i++)
                    {
                        newItem.SubItems[i].ForeColor = this.Items[itemIndex].SubItems[i].ForeColor;
                        newItem.SubItems[i].BackColor = this.Items[itemIndex].SubItems[i].BackColor;
                    }
                    insertItems.Add(newItem);
                }
            }

            // create a new list item and add it to the listing of items that should be added
            string test = drgevent.Data.GetType().ToString();

            //ArrayList insertItems = new ArrayList(draggedItems.Length);

            //foreach (string draggedItem in draggedItems)
            //{
            //    // split the data so we can get the control name and the sub item data
            //    string[] data = draggedItem.Split('\x1');
            //    controlName = data[0];
            //    int itemIndex = int.Parse(data[1]);
            //    string[] subItems = new string[this.Columns.Count];
            //    for (int i = 0; i < subItems.Length; i++)
            //    {
            //        subItems[i] = this.Items[itemIndex].SubItems[i].Text;
            //    }
            //    ListViewItem newItem = new ListViewItem(subItems);
            //    newItem.Checked = this.Items[itemIndex].Checked;
            //    newItem.ImageIndex = this.Items[itemIndex].ImageIndex;
            //    newItem.Tag = this.Items[itemIndex].Tag;
            //    for (int i = 1; i < newItem.SubItems.Count; i++)
            //    {
            //        newItem.UseItemStyleForSubItems = this.Items[itemIndex].UseItemStyleForSubItems;
            //        newItem.SubItems[i].ForeColor = this.Items[itemIndex].SubItems[i].ForeColor;
            //        newItem.SubItems[i].BackColor = this.Items[itemIndex].SubItems[i].BackColor;
            //    }
            //    insertItems.Add(newItem);
            //}

            if (hoverItem == null)
            {
                // the user does not wish to re-order the items, just append to the end
                for (int i = 0; i < insertItems.Count; i++)
                {
                    ListViewItem newItem = (ListViewItem)insertItems[i];
                    base.Items.Add(newItem);
                }
            }
            else
            {
                // the user wishes to re-order the items

                // get the index of the hover item
                int hoverIndex = hoverItem.Index;

                // determine if the items to be dropped are from
                // this list view. If they are, perform a hack
                // to increment the hover index so that the items
                // get moved properly.
                if (base.Name == controlName)
                {
                    if (base.SelectedItems.Count > 0 && hoverIndex > base.SelectedItems[0].Index)
                    {
                        hoverIndex++;
                    }
                }

                // insert the new items into the list view
                // by inserting the items reversely from the array list
                for (int i = insertItems.Count - 1; i >= 0; i--)
                {
                    ListViewItem newItem = (ListViewItem)insertItems[i];
                    base.Items.Insert(hoverIndex, newItem);
                }
            }


            // find the sender list view control
            DragAndDropListView listView = FindListView(this.FindForm(), controlName);

            // remove all the selected items from the previous list view
            // if the list view was found
            if (localSource && listView != null)
            {
                foreach (ListViewItem itemToRemove in listView.SelectedItems)
                {
                    listView.Items.Remove(itemToRemove);
                }
            }

            // set the back color of the previous item, then nullify it
            if (m_previousItem != null)
            {
                m_previousItem = null;
            }

            this.Invalidate();

            // call the base on drag drop to raise the event
            base.OnDragDrop(drgevent);
        }
        private void TraverseDir(InventoryNode node, string path)
        {
            var nodes = new List <InventoryNode>(node.Nodes.Values);

            foreach (InventoryNode n in nodes)
            {
                traversed++;
                try
                {
                    if (IsHandleCreated && (traversed % 13 == 0))
                    {
                        BeginInvoke(new MethodInvoker(() =>
                        {
                            lblStatus.Text = string.Format("Traversed {0} nodes...", traversed);
                        }));
                    }

                    if (n.Data is InventoryFolder)
                    {
                        WriteCSVLine("Folder", path, n.Data.Name, "", "", "", "");
                        TraverseDir(n, Path.Combine(path, RadegastInstance.SafeFileName(n.Data.Name)));
                    }
                    else
                    {
                        InventoryItem item      = (InventoryItem)n.Data;
                        string        creator   = item.CreatorID == UUID.Zero ? string.Empty : instance.Names.Get(item.CreatorID, true);
                        string        lastOwner = item.LastOwnerID == UUID.Zero ? string.Empty : instance.Names.Get(item.LastOwnerID, true);
                        string        type      = item.AssetType.ToString();
                        if (item.InventoryType == InventoryType.Wearable)
                        {
                            type = ((WearableType)item.Flags).ToString();
                        }
                        string created = item.CreationDate.ToString("yyyy-MM-dd HH:mm:ss");
                        WriteCSVLine(type, path, item.Name, item.Description, created, creator, lastOwner);

                        PermissionMask fullPerm = PermissionMask.Modify | PermissionMask.Copy | PermissionMask.Transfer;
                        if ((item.Permissions.OwnerMask & fullPerm) != fullPerm)
                        {
                            continue;
                        }

                        string filePartial = Path.Combine(path, RadegastInstance.SafeFileName(n.Data.Name));
                        string fullName    = folderName + filePartial;
                        switch (item.AssetType)
                        {
                        case AssetType.LSLText:
                            client.Settings.USE_ASSET_CACHE = false;
                            fullName += ".lsl";
                            break;

                        case AssetType.Notecard: fullName += ".txt"; break;

                        case AssetType.Texture: fullName += ".png"; break;

                        default: fullName += ".bin"; break;
                        }
                        string dirName = Path.GetDirectoryName(fullName);
                        bool   dateOK  = item.CreationDate > new DateTime(1970, 1, 2);

                        if (
                            (item.AssetType == AssetType.LSLText && cbScripts.Checked) ||
                            (item.AssetType == AssetType.Notecard && cbNoteCards.Checked) ||
                            (item.AssetType == AssetType.Texture && cbImages.Checked)
                            )
                        {
                            ListViewItem lvi = new ListViewItem
                            {
                                Text = n.Data.Name, Tag = n.Data, Name = n.Data.UUID.ToString()
                            };

                            ListViewItem.ListViewSubItem fileName = new ListViewItem.ListViewSubItem(lvi, filePartial);
                            lvi.SubItems.Add(fileName);

                            ListViewItem.ListViewSubItem status = new ListViewItem.ListViewSubItem(lvi, "Fetching asset");
                            lvi.SubItems.Add(status);

                            //bool cached = dateOK && File.Exists(fullName) && File.GetCreationTimeUtc(fullName) == item.CreationDate;

                            //if (cached)
                            //{
                            //    status.Text = "Cached";
                            //}

                            BeginInvoke(new MethodInvoker(() =>
                            {
                                lvwFiles.Items.Add(lvi);
                                lvwFiles.EnsureVisible(lvwFiles.Items.Count - 1);
                            }));

                            //if (cached) continue;

                            Asset receivedAsset = null;
                            using (AutoResetEvent done = new AutoResetEvent(false))
                            {
                                if (item.AssetType == AssetType.Texture)
                                {
                                    client.Assets.RequestImage(item.AssetUUID, (state, asset) =>
                                    {
                                        if (state == TextureRequestState.Finished && asset != null && asset.Decode())
                                        {
                                            receivedAsset = asset;
                                            done.Set();
                                        }
                                    });
                                }
                                else
                                {
                                    var transferID = UUID.Random();
                                    client.Assets.RequestInventoryAsset(item, true, transferID, (transfer, asset) =>
                                    {
                                        if (transfer.Success && transfer.ID == transferID)
                                        {
                                            receivedAsset = asset;
                                        }
                                        done.Set();
                                    }
                                                                        );
                                }

                                done.WaitOne(30 * 1000, false);
                            }

                            client.Settings.USE_ASSET_CACHE = true;

                            if (receivedAsset == null)
                            {
                                BeginInvoke(new MethodInvoker(() => status.Text = "Failed to fetch asset"));
                            }
                            else
                            {
                                BeginInvoke(new MethodInvoker(() => status.Text = "Saving..."));

                                try
                                {
                                    if (!Directory.Exists(dirName))
                                    {
                                        Directory.CreateDirectory(dirName);
                                    }

                                    switch (item.AssetType)
                                    {
                                    case AssetType.Notecard:
                                        AssetNotecard note = (AssetNotecard)receivedAsset;
                                        if (note.Decode())
                                        {
                                            File.WriteAllText(fullName, note.BodyText, System.Text.Encoding.UTF8);
                                            if (dateOK)
                                            {
                                                File.SetCreationTimeUtc(fullName, item.CreationDate);
                                                File.SetLastWriteTimeUtc(fullName, item.CreationDate);
                                            }
                                        }
                                        else
                                        {
                                            Logger.Log(string.Format("Falied to decode asset for '{0}' - {1}", item.Name, receivedAsset.AssetID), Helpers.LogLevel.Warning, client);
                                        }

                                        break;

                                    case AssetType.LSLText:
                                        AssetScriptText script = (AssetScriptText)receivedAsset;
                                        if (script.Decode())
                                        {
                                            File.WriteAllText(fullName, script.Source, System.Text.Encoding.UTF8);
                                            if (dateOK)
                                            {
                                                File.SetCreationTimeUtc(fullName, item.CreationDate);
                                                File.SetLastWriteTimeUtc(fullName, item.CreationDate);
                                            }
                                        }
                                        else
                                        {
                                            Logger.Log(string.Format("Falied to decode asset for '{0}' - {1}", item.Name, receivedAsset.AssetID), Helpers.LogLevel.Warning, client);
                                        }

                                        break;

                                    case AssetType.Texture:
                                        AssetTexture imgAsset = (AssetTexture)receivedAsset;
                                        var          img      = LoadTGAClass.LoadTGA(new MemoryStream(imgAsset.Image.ExportTGA()));
                                        img.Save(fullName, System.Drawing.Imaging.ImageFormat.Png);
                                        if (dateOK)
                                        {
                                            File.SetCreationTimeUtc(fullName, item.CreationDate);
                                            File.SetLastWriteTimeUtc(fullName, item.CreationDate);
                                        }
                                        break;
                                    }

                                    BeginInvoke(new MethodInvoker(() =>
                                    {
                                        fileName.Text  = fullName;
                                        status.Text    = "Saved";
                                        lblStatus.Text = string.Format("Saved {0} items", ++fetched);
                                    }));
                                }
                                catch (Exception ex)
                                {
                                    BeginInvoke(new MethodInvoker(() => status.Text = "Failed to save " + Path.GetFileName(fullName) + ": " + ex.Message));
                                }
                            }
                        }
                    }
                }
                catch { }
            }
        }
        /// <summary>
        /// Asssign controls to the summary viewer
        /// </summary>
        /// <param name="BaseData">The base data for the display</param>
        public void SetControls(MM_DataSet_Base BaseData)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new SafeSetControls(SetControls), BaseData);
            }
            else
            {
                //Assign our base table and integration layer
                this.BaseData = BaseData;


                //Go through the data tables, and tally up both total and by KV level into the columns
                this.Items.Clear();
                foreach (DataTable dt in BaseData.Data.Tables)
                {
                    if (dt.Rows.Count > 0)
                    {
                        ListViewItem ElementRow = this.Items.Add(dt.TableName);
                        ElementRow.UseItemStyleForSubItems = false;
                        ElementRow.SubItems.Add(dt.Rows.Count.ToString("#,##0")).ForeColor = Color.White;
                        ElementRow.Tag = dt;
                        Dictionary <MM_KVLevel, int> KVLevels = new Dictionary <MM_KVLevel, int>(MM_Repository.KVLevels.Count);
                        foreach (MM_KVLevel KVLevel in MM_Repository.KVLevels.Values)
                        {
                            if (KVLevel.Permitted)
                            {
                                KVLevels.Add(KVLevel, 0);
                            }
                        }

                        foreach (DataRow dr in dt.Rows)
                        {
                            MM_Element Elem = dr["TEID"] as MM_Element;
                            if (Elem is MM_Substation)
                            {
                                foreach (MM_KVLevel KVLevel in (Elem as MM_Substation).KVLevels)
                                {
                                    if (KVLevel.Permitted)
                                    {
                                        KVLevels[KVLevel]++;
                                    }
                                }
                            }
                            else if (Elem is MM_Transformer)
                            {
                                foreach (MM_TransformerWinding Winding in (Elem as MM_Transformer).Windings)
                                {
                                    if (Winding.KVLevel != null && Winding.KVLevel.Permitted)
                                    {
                                        KVLevels[Winding.KVLevel]++;
                                    }
                                }
                            }
                            else if (Elem.KVLevel != null)
                            {
                                KVLevels[Elem.KVLevel]++;
                            }
                        }

                        foreach (KeyValuePair <MM_KVLevel, int> KVLevel in KVLevels)
                        {
                            if (KVLevel.Value == 0)
                            {
                                ElementRow.SubItems.Add("").Tag = KVLevel;
                            }
                            else
                            {
                                ListViewItem.ListViewSubItem SubItem = ElementRow.SubItems.Add(KVLevel.Value.ToString("#,##0"));
                                SubItem.ForeColor = KVLevel.Key.Energized.ForeColor;
                                SubItem.Tag       = KVLevel;
                            }
                        }
                    }
                }
                this.Sorting = SortOrder.Ascending;
                this.Sort();
                MM_Repository.ViewChanged += new MM_Repository.ViewChangedDelegate(MM_Repository_ViewChanged);
            }
        }
Exemple #30
0
        private void b_export_list_Click(object sender, EventArgs e)
        {
            if (ConvertProcessor.in_process)
            {
                return;
            }
            ;

            ExportersListForm form = new ExportersListForm();

            for (int op = 0; conv_core.workbench.formats.count > op; op++)
            {
                conv_core.cFormat format = conv_core.workbench.formats[op];
                if (format.has_writer)
                {
                    form.m_all_items.Add(format.name);
                }
                ;
            }
            ;

            foreach (ColumnHeader hdr in m_formats)
            {
                form.m_selected_items.Add(hdr.Text);
            }
            ;

            switch (form.ShowDialog(this))
            {
            case DialogResult.OK: {
                int hdr_id = 0;
                while (m_formats.Count > hdr_id)
                {
                    ColumnHeader hdr = m_formats[hdr_id];
                    if (0 > form.m_selected_items.FindIndex(delegate(string str){ return(hdr.Text == str); }))
                    {
                        m_formats.Remove(hdr);

                        foreach (ListViewItem li in lv_files.Items)
                        {
                            li.SubItems.RemoveAt(hdr.Index);
                        }
                        ;

                        lv_files.Columns.Remove(hdr);

                        t_mod.Enabled = true;
                    }
                    else
                    {
                        hdr_id++;
                    };
                }
                ;

                foreach (string fmt in form.m_selected_items)
                {
                    if (0 > m_formats.FindIndex(delegate(ColumnHeader hdr) { return(fmt == hdr.Text); }))
                    {
                        conv_core.cFormat format = conv_core.workbench.formats[fmt];

                        foreach (ListViewItem li in lv_files.Items)
                        {
                            ListViewItem.ListViewSubItem lsi = li.SubItems.Add(
                                Path.GetFileNameWithoutExtension(li.Text) + "." + format.ext
                                );
                            lsi.Tag = new conv_core.cImageFile(t_base_dir.Text + "\\" + lsi.Text);
                        }
                        ;

                        add_format(fmt);

                        t_mod.Enabled = true;
                    }
                    ;
                }
                ;
            } break;
            }
            ;

            form.Dispose();
        }