Delete row from Datatable with an iteration

1 Mar 2018 In: .net
List<DataRow> toDelete = new List<DataRow>();
                foreach (DataRow dr in dt_kimaylmt.Rows)
                {
                    if (dr["DepartmentId"].ToString() == "" || dr["FleetId"].ToString().Length == 0)
                    {
                        toDelete.Add(dr);
                    }
                }

                foreach (DataRow dr in toDelete)
                {
                    dt_kimaylmt.Rows.Remove(dr);
                }
               

                dt_kimaylmt.AcceptChanges();

Repeater Footer Summary

1 Ağu 2017 In: .net
        protected void rpt_kayitlar_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header) { Session["ktp"] = 0m; }
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { Session["ktp"] = (decimal)Session["ktp"] + (decimal)DataBinder.Eval(e.Item.DataItem, "Tutar");  }
            if (e.Item.ItemType == ListItemType.Footer) { ((Label)e.Item.FindControl("lbl_t")).Text = ((decimal)Session["ktp"]).ToString("N2"); }
        }

RadioButton group name solution for repater

25 Şub 2017 In: .net, ipucu

I got a templated control (a repeater) listing some text and other markup. Each item has a radiobutton associated with it, making it possible for the user to select ONE of the items created by the repeater.

The repeater writes the radiobutton setting its ID and NAME generated with the default ASP.NET naming convention making each radiobutton a full 'group'. This means all radiobuttons are independent on each other, which again unfortunately means I can select all radiobuttons at the same time. The radiobutton has the clever attribute 'groupname' used to set a common name, so they get grouped together and thus should be dependant (so I can only select one at a time). The problem is - this doesn't work - the repeater makes sure the id and thus the name (which controls the grouping) are different.
 
With this JS method, you can set name with a constant name. And that s solved :) 
 
    function set_radio_name() {
        $("[type=radio]").each(function (i) {
            var name = $(this).attr("name");
            var splitted = name.split("$");
            $(this).attr("name", "sec");
        });
    };

    $(document).ready(function () {
        set_radio_name();
    });

Merhabalar,

bazı webservis lerini Visual Studio da "Add Reference" ile projemize ekleyince, genellikle tür dönüşümlerinden kaynaklı Reference.cs de otomatik üretilen kodlar dogru olmuyor ve WS e veri yollamak veya almakta sorunlar olabiliyor.

Bu aşagıda kod ile VS2015 ve VS2017 de web servisini projemize referans olarak eklemeden methodları çağırabiliyoruz.

  public XmlDocument CallWs_xxx(string URL, string SoapAction)

        {

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(urlofws); //?wsdl i unutma

            wr.ContentType = "application/soap+xml;charset=UTF-8;action=\"" + SoapAction + "\"";

            wr.Method = "POST";

            //HttpWebRequest request = CreateWebRequest("http://ssaspanorama.com/integrationwebservice.asmx?wsdl", "IntegrationSendEntitySetWithLogin");

            XmlDocument soapEnvelopeXml = new XmlDocument();

            soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>

<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:int=""http://integration.univera.com.tr"">

   <soap:Header/>

   <soap:Body>

      <int:IntegrationSendEntitySetWithLogin>

         <!--Optional:-->

         <!--Optional:-->

         <!--Optional:-->

      </int:IntegrationSendEntitySetWithLogin>

   </soap:Body>

</soap:Envelope>");

            using (Stream stream = wr.GetRequestStream())

            {

                soapEnvelopeXml.Save(stream);

            }

            using (WebResponse response = wr.GetResponse())

            {

                using (StreamReader rd = new StreamReader(response.GetResponseStream()))

                {

                    string SoapResults = rd.ReadToEnd();

                    return new XmlDocument().LoadXml(SoapResults);

                }

            }

        }

 


When working with a solution for a longer period, Visual Studio gets slower and slower.
Especially the debugger becomes unusable, because it needs some extra seconds to start and to stop.
When you remove your .SUO file, Visual Studio 2010 becomes fast again, and the debugger starts and stops instantly.
 
Eger uzun zamandır üzerinde çalıştıgınız Visual studio 2010 projeniz açıp-kapatırken veya debug yaparken çok yavaşladıysa örnegin debug başlatmak ve durdurmak 20-30 saniye sürüyorsa,
tek yapmanız gerek projenize ait .SUO dosyasını silmeniz yeterli.
Projenizi yeniden açıp kapattıgınız da ilk günkü gibi hızlı :) 

Windows Form Application Tricks

26 Ağu 2014 In: .net, ipucu
        public class ComboboxItem
        {
            public string Text { get; set; }
            public object Value { get; set; }

            public ComboboxItem(string text, string value)
            {
                this.Text = text;
                this.Value = value;
            }
            public override string ToString()
            {
                return Text;
            }
        }
 
        public void entermi_keydown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (sender is TextBox)
                    if (((TextBox)sender).Name == "txt_sifre")
                    {
                        btn_giris(sender, e);
                        return;
                    }
                SendKeys.Send("{TAB}");
            }
        }
 
        private void txt_textbox_Enter(object sender, System.EventArgs e)
        {
            TextBox a = (TextBox)sender;
            a.BackColor = Color.Red;
            a.ForeColor = Color.White;
        }
 
        private void txt_textbox_Leave(object sender, System.EventArgs e)
        {
            TextBox a = (TextBox)sender;
            a.BackColor = Color.White;
            a.ForeColor = Color.Black;
        }

Metni kelime kelime satıra sıgdırmaca

12 May 2014 In: .net, ipucu

Eger satır limiti var ve yazdıklarımız bu satırdan buyuk ise, kelime bütünlügünü bozmadan kelimeyi alt satıra taşıma ve devam etme, çok özensizce yazılmış üstünden kesinlikle geçilmeli, dinamik satır sayısı gibi :)
 
  string satir1 = "";
                string satir2 = "";
                string satir3 = "";
                string[] kelimeler = new string[1] { "" };
                kelimeler = MSipAciklama.Split(new string[1] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (kelimeler.Length > 0)
                {
                    int kacci = 0;
                    int limit = (int)g.MeasureString("SATIRIN UZUNLUGUNU BULMAK İÇİN KULLANDIGIM DUMMY METIN ", InvoiceFontBaslik).Width; //40 karakter gibide olabilir burası; //572point
                    int toplam = 0;
                    for (int i = 0; i < kelimeler.Length; i++)
                    {
                        if (toplam + (int)g.MeasureString(kelimeler[i] + " ", InvoiceFontBaslik).Width < limit * 1)
                        {
                            toplam += (int)g.MeasureString(kelimeler[i] + " ", InvoiceFontBaslik).Width;
                            satir1 += kelimeler[i] + " ";
                        }
                        else
                            if (toplam + (int)g.MeasureString(kelimeler[i] + " ", InvoiceFontBaslik).Width < limit * 2)
                            {
                                toplam += (int)g.MeasureString(kelimeler[i] + " ", InvoiceFontBaslik).Width;
                                satir2 += kelimeler[i] + " ";
                            }
                            else
                                if (toplam + (int)g.MeasureString(kelimeler[i] + " ", InvoiceFontBaslik).Width < limit * 3)
                                {
                                    toplam += (int)g.MeasureString(kelimeler[i] + " ", InvoiceFontBaslik).Width;
                                    satir3 += kelimeler[i] + " ";
                                }
                    }
                }
                if (satir1.Length > 0)
                {
                    FieldValue = satir1;
                    g.DrawString(FieldValue, InvoiceFont, BlackBrush, CurrentX + 120, CurrentY + 2);
                    CurrentY = CurrentY + InvoiceFontHeight;
                }
                if (satir2.Length > 0)
                {
                    FieldValue = satir2;
                    g.DrawString(FieldValue, InvoiceFont, BlackBrush, CurrentX + 120, CurrentY + 2);
                    CurrentY = CurrentY + InvoiceFontHeight;
                }
                if (satir3.Length > 0)
                {
                    FieldValue = satir3;
                    g.DrawString(FieldValue, InvoiceFont, BlackBrush, CurrentX + 120, CurrentY + 2);
                    CurrentY = CurrentY + InvoiceFontHeight;
                }

 
 

DataTable to PDF and Excel

2 Şub 2014 In: .net
   public void PDFYapsana(string dadi, string html)
        {
            try
            {
                Byte[] bytes;
                MemoryStream ms = new MemoryStream();
                Document doc = new Document();
                PdfWriter writer = PdfWriter.GetInstance(doc, ms);
                doc.Open();

                var htmlText = "";
                try
                {
                    //Our sample HTML and CSS
                    htmlText = html;//@"<div style='height:50px'>&nbsp; SELAMLAR <br/></div>";

                    var example_css = @"
.zui-table {
    border: solid 1px #DDEEEE;
    border-collapse: collapse;
    border-spacing: 0;
    font: normal 13px Arial, sans-serif;
}
.zui-table thead th {
    background-color: #DDEFEF;
    border: solid 1px #DDEEEE;
    color: #336B6B;
    padding: 10px;
    text-align: left;
    text-shadow: 1px 1px 1px #fff;
}
.zui-table tbody td {
    border: solid 1px #DDEEEE;
    color: #333;
    padding: 10px;
    text-shadow: 1px 1px 1px #fff;
}";
                    MemoryStream msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css));
                    MemoryStream msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlText));
                    doc.Open();
                    iTextSharp.tool.xml.XMLWorkerHelper aa = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                    writer.Open();
                    doc.Open();
                    aa.ParseXHtml(writer, doc, msHtml, msCss);
                    doc.Close();
                    bytes = ms.ToArray();
                    var testFile = HttpContext.Current.Server.MapPath("Ups/" + dadi + ".pdf");
// Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
                    System.IO.File.WriteAllBytes(testFile, bytes);
                }
                catch (Exception exi)
                {
    
                }
            }
            catch (Exception ex)
            {

            }
        }
 
/* Kullanımı
  string h = @"
<html><body>
<table class='zui-table'>
<thead><tr><th></th><th>QR</th><th>USER</th><th>PROJECT</th></tr></thead>
<tbody>                                                
<tr><td>1</td><td><img src=""https://www.com/QRS/110.jpg"" height='80px'/></td><td>cb1</td><td>ZONE1</td></tr>
</tbody></table></body></html>";
            PDFYapsana("b", h);
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
            //Response.TransmitFile("https://www.com/UPS/b.pdf");
            Response.TransmitFile(Server.MapPath(".")+ "/UPS/b.pdf");
            Response.End();
*/ 
 
 
---------------------------------------
 
        //Export Datatable to PDF
        public void DT2PDF(DataTable dt)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            //rpt_kayitlar.RenderControl(hw);
            DataGrid dg = new DataGrid();
            dg.DataSource = dt;
            dg.DataBind();
            //hw. = "";
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }
 
 
----------------------------------------
 
//Export Repeater to Excel
 
  protected void ExportToExcel(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            foreach (RepeaterItem item in rpt_kayitlar.Items)
            {
                List<System.Web.UI.Control> controls = new List<System.Web.UI.Control>();
                foreach (System.Web.UI.Control control in item.Controls)
                {
                    controls.Add(control);
                }
                int i = 0;
                foreach (System.Web.UI.Control control in controls)
                {
                    switch (control.GetType().Name)
                    {
                        case "CheckBox":
                            //item.Controls.AddAt(i + 1, new Literal { Text = (control as TextBox).Text });
                            item.Controls.RemoveAt(i);
                            break;

                        case "Button":
                            //item.Controls.AddAt(i + 1, new Literal { Text = (control as TextBox).Text });
                            item.Controls.RemoveAt(i);
                            break;

                        case "LinkButton":
                            //item.Controls.AddAt(i + 1, new Literal { Text = (control as TextBox).Text });
                            item.Controls.RemoveAt(i);
                            break;
                        
                    }
                    i++;
                }
            }
            rpt_kayitlar.RenderControl(hw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        } 
 
 
----------------------------------------
 
    protected void PrintExcel(object sender, EventArgs e)
        {
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=file.xls");
            Response.ContentType = "application/vnd.ms-excel";
            string filePath = Server.MapPath("~/PDF/Capture.PNG.png");
            System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(filePath);
            string imagepath = string.Format("<img src='{0}' width='{1}' height='{2}'/>", filePath, imgPhoto.Width, imgPhoto.Height);
            var sb = new StringBuilder();


            RepeaterItem item1;


            sb.Append("<table border='1'>");
            sb.Append("<tr>");
            sb.Append("<th>");
            sb.Append("Kasa Numarası");
            sb.Append("<th>");

            sb.Append("Cari No");
            sb.Append("<th>");
            sb.Append("Cari Hesap");
            sb.Append("<th>");
            sb.Append("Tarih");

            sb.Append("<th>");
            sb.Append("Açıklama");
            sb.Append("<th>");

            sb.Append("ProjeKodu");
            sb.Append("<th>");
            sb.Append("Tutar");
            sb.Append("</th></th></th></th></th></th></th></tr>");


            foreach (RepeaterItem item in rpt_kayitlar.Items)
            {
                sb.Append("<tr>");
                sb.Append("<td>");
                sb.Append(imagepath);
                sb.Append("<td>");

                sb.Append(((Label)item.FindControl("Label2")).Text);
                sb.Append("<td>");
                sb.Append(((Label)item.FindControl("Label3")).Text);
                sb.Append("<td>");
                sb.Append(((Label)item.FindControl("Label4")).Text);
                sb.Append("<td>");
                sb.Append(((Label)item.FindControl("Label5")).Text);
                sb.Append("<td>");
                sb.Append(((Label)item.FindControl("Label6")).Text);
                sb.Append("<td>");
                sb.Append(((Label)item.FindControl("Label7")).Text);
                sb.Append("<td>");
                sb.Append(((Label)item.FindControl("Label8")).Text);
                sb.Append("<td>");
                sb.Append(((Label)item.FindControl("Label9")).Text);
                sb.Append("<td>");
                sb.Append(((Label)item.FindControl("Label10")).Text);
                sb.Append("<td>");
                sb.Append(((Label)item.FindControl("Label11")).Text);
                sb.Append("</td></td></td></td></td></td></td></td></td></td></td></tr>");
                imgPhoto.Dispose();
            }
            sb.Append("</table>");
            Response.ContentType = "application/vnd.xls";
            Response.Write(sb.ToString());
            imgPhoto.Dispose();
            Response.Flush();
            Response.End();

}



 
  ------------------------
 
print html table to print
 
 
 <script type='text/javascript'>
         var tableToExcel = (function () {
             var uri = 'data:application/vnd.ms-excel;base64,'
                , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> <meta charset="utf-8"></head><body><table>{table}</table></body></html>'
                , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
                , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
             return function (table, name) {
                 if (!table.nodeType) table = document.getElementById(table)
                 var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
                 window.location.href = uri + base64(format(template, ctx))
             }
         })()
    </script> 
 
 
------------------------------
 
JS ile print only div
 
        function printData() {
    var divToPrint = document.getElementById("gridi");
    newWin = window.open("", "newWin");
    newWin.document.write(divToPrint.outerHTML);
    setTimeout(function () {
        newWin.print();
    }, 1000)
    // newWin.close();

Ben Kimim ?

Celiker BahceciMerhabalar, ben Çeliker BAHÇECİ. 2004 den beri özel sektörde bilgisayar mühendisligi ve egitmenlik yapıyorum. Yine aynı yılın Ekim ayından beri sitemde .Net ile programlama ve hayat görüşüm ile ilgili makalelerimi yayınlıyorum. Blogum dışında Yazgelistir.com, mobilnedir.com gibi ineta kapsamındaki bir çok siteye Microsoft teknolojileri ile ilgili yazılar yazmaktayım.
Bu site ile sizinde hayatınızı anlamlandırmanızda bir parça katkımın olması dilegiyle...