Tuesday 31 March 2015

Set String Format for DateTime using c#



 There are following types of formates below-

DateTime dt = new DateTime(2015, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 15 015 2015"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2015 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2015 16:05:07" - german (de-DE)

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2015"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2015"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2015"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2015"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/15"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2015"

// Time Formate

String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2015"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2015"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2015 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2015 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2015 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2015 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2015"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2015 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2015-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2015-03-09 16:05:07Z"            UniversalSortableDateTime


Change the ForeColor of individual items in a ComboBox (C# Winforms)


Following steps-

1-  select drowmode property to ownerDrawFixed

2-

private void Form2_Load(object sender, EventArgs e)
        {
         
                this.comboBox1.Items.Add("Test1");
                this.comboBox1.Items.Add("Test2");
                this.comboBox1.Items.Add("Test3");
                this.comboBox1.Items.Add("Test4");
                this.comboBox1.Items.Add("Test5");
                this.comboBox1.Items.Add("Test6");
           
        }

        private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            // Draw the background
            e.DrawBackground();
            // Get the item text   
            string text = ((ComboBox)sender).Items[e.Index].ToString();
            // Determine the forecolor based on whether or not the item is selected   
            Brush brush;
            if (IsItemDisabled(e.Index))// compare  date with your list. 
            {
                brush = Brushes.Red;
            }
            else
            {
                brush = Brushes.Gray;
            }

            // Draw the text   
            e.Graphics.DrawString(text, ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);
        }

        void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IsItemDisabled(comboBox1.SelectedIndex))
                comboBox1.SelectedIndex = -1;
        }

        bool IsItemDisabled(int index)
        {
            // We are disabling item based on Index, you can have your logic here
            return index % 2 == 1;
        }


AngularJS Convert Number to Currency Format


//HTML

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Limit Number to 2 decmial places in Angularjs</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
      var myApp = angular.module('divid', [])
      myApp.controller("expressionController", function ($scope) {
      $scope.amount = 99999.56;
      });
    </script>
  </head>
  <body>
    <form id="form1">
      <div data-ng-app="divid" data-ng-controller="expressionController">
        <input type="number" ng-model="amount">
          <br/>
          default currency symbol ($): <span>{{amount | currency}}</span><br>
            <!--By default its $ sign-->
            no fractions: <span>{{amount | currency:"Currency Symbol  "}}</span><br>
              <!--Currency Symbol - Put your currency symbol -->
              no of fractions:<span>{{amount | currency:"Currency Symbol  ":1}}</span><br>
                <!-- :1 decimal place-->
                no of fractions:<span>{{amount | currency:"Currency Symbol  ":0}}</span><!-- :1 decimal place-->
                <!---->
              </div>
    </form>
  </body>

</html>


// Result


Wednesday 25 March 2015

Export String to PDF using C# with iTextSharp DLL


//add name space

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using iTextSharp.text.html.simpleparser;

using iTextSharp.text;


//String

StringBuilder strBuilder = new StringBuilder();
            strBuilder.Append("<h1 title='Header' align='Center'>Writing To Word File using windows form in c#</h1> ".ToString());
            strBuilder.Append("<br>".ToString());
            strBuilder.Append("<table border='1' align='Center'>".ToString());
            strBuilder.Append("<tr>".ToString());
            strBuilder.Append("<td style='width:30%;color:green'><b>Krishna Kumar Chaturvedi</b></td>".ToString());
            strBuilder.Append("<td style='width:30%;color:red'>India</td>".ToString());
            strBuilder.Append("<td style='width:30%;color:red'>Software developer</td>".ToString());
            strBuilder.Append("</tr>".ToString());
            strBuilder.Append("</table>".ToString());
            string strPath = textBox1.Text + "Test" + DateTime.Now.ToString("hhmmss") + ".pdf";

//Create PDF
using (FileStream stream = new FileStream(strPath, FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                PdfWriter.GetInstance(pdfDoc, stream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                stream.Close();
            }

//result



Tuesday 24 March 2015

Show Number formate Columns to Text formate in excel export in asp.net, C#



            string datestyle = @"<style> .nf{mso-number-format:\@;}</style>";

//add this string to your export data table
            HttpResponse Response = HttpContext.Current.Response;
            string filename = "Test" + "_" + System.DateTime.Now.ToString("MMddyy_hhmmss") + ".doc";
            Response.Clear();
            Response.AddHeader("content-disposition""attachment;filename=" + filename);
            Response.Charset = "";
            Response.ContentType = "application/xls";
            System.IO.StringWriter WriteItem = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlText = newHtmlTextWriter(WriteItem);

            Response.Write(datestyle);
            Response.Write(strBuilder.ToString());
            Response.End();

Print report in MS Word using asp.net C# without using MS word dll




Step 1- Click on Print button


private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.Append("<h1 title='Header' align='Center'>Writing To Word File using windows form in c#</h1> ".ToString());
            strBuilder.Append("<br>".ToString());
            strBuilder.Append("<table border='1' align='Center'>".ToString());
            strBuilder.Append("<tr>".ToString());
            strBuilder.Append("<td style='width:30%;color:green'><b>Krishna Kumar Chaturvedi</b></td>".ToString());
            strBuilder.Append("<td style='width:30%;color:red'>India</td>".ToString());
            strBuilder.Append("<td style='width:30%;color:red'>Software developer</td>".ToString());
            strBuilder.Append("</tr>".ToString());
            strBuilder.Append("</table>".ToString());

  string datestyle = @"<style> .nf{mso-number-format:\@;}</style>";
            HttpResponse Response = HttpContext.Current.Response;
            string filename = "Test" + "_" + System.DateTime.Now.ToString("MMddyy_hhmmss") + ".doc";
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + filename);
            Response.Charset = "";
            Response.ContentType = "application/xls";
            System.IO.StringWriter WriteItem = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);

            Response.Write(datestyle);
            Response.Write(strBuilder.ToString());
            Response.End();

        }




//Result

Print Report in MS word using StringBuilder in c# without using MS word dll



Step 1- Create a fileupload dialogue to set path of the file


Step 2- Write code on print button Click event

private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.Append("<h1 title='Header' align='Center'>Writing To Word File using windows form in c#</h1> ".ToString());
            strBuilder.Append("<br>".ToString());
            strBuilder.Append("<table border='1' align='Center'>".ToString());
            strBuilder.Append("<tr>".ToString());
            strBuilder.Append("<td style='width:100px;color:green'><b>amiT</b></td>".ToString());
            strBuilder.Append("<td style='width:100px;color:red'>India</td>".ToString());
            strBuilder.Append("</tr>".ToString());
            strBuilder.Append("</table>".ToString());
            string strPath =textBox1.Text+"Test"+DateTime.Now.ToString("hhmmss")+".doc";
            FileStream fStream = File.Create(strPath);
            fStream.Close();
            StreamWriter sWriter = new StreamWriter(strPath);
            sWriter.Write(strBuilder);
            sWriter.Close();

        }

//Result


Wednesday 11 March 2015

How to Export Encoded Data into CSV Files using asp.net c#



//Data Tabel




//HTML
<asp:Button ID="btnExport" runat="server" Text="Button" OnClick="btnExport_Click" />

//Code Behind

protected void btnExport_Click(object sender, EventArgs e)
    {
        DataTable dt = GetData();
        StringBuilder builder = new StringBuilder();
        var count = 0;

        // write header in String Builder
        foreach (DataColumn column in dt.Columns)
        {
            count++;
            string content = column.ColumnName + "";
            content = content.Replace("\"", "\"\"");
            builder.Append(string.Format("{0}{1}{0}", Convert.ToChar(34), content));

            if (count < dt.Columns.Count)
                builder.Append(",");
        }
        builder.Append(Environment.NewLine);

        //Write content in String Builder
        foreach (DataRow row in dt.Rows)
        {
            for (int i = 0; i < row.ItemArray.Length; i++)
            {
                if (!Convert.IsDBNull(row[i]))
                {
                    string content = row[i].ToString() + "";
                    content = content.Replace("\"", "\"\"");
                    builder.Append(string.Format("{0}{1}{0}", Convert.ToChar(34), content));

                    if (i < row.ItemArray.Length - 1)
                        builder.Append(",");
                }
            }
            builder.Append(Environment.NewLine);
        }

        // get file and write inside file
        using (var streamWriter = new StreamWriter(@"C://Users//Vipin Gehlot//Desktop//yy.csv", false, Encoding.UTF8))
        {
            streamWriter.Write(builder.ToString());
            streamWriter.Flush();
            streamWriter.Close();
        }
    }
}



//Result




Excel Sort values in ascending order using function TEXTJOIN

 Excel ::  Text ::  1,3,5,2,9,5,11 Result :: 1,2,3,5,5,9,11 Formula ::     TEXTJOIN ( ",",1,SORT(MID(SUBSTITUTE( A1 ,","...