Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, 24 May 2018

Multiple Catch Blocks for Try Block in C#



              In this article, I would like to know you about multiple catch blocks for try block.
Actually the Exception class is the super class for all the exceptions, so this Exception class catch block should be at end of all catch blocks, if not it shows an error message at compile time only i.e., A previous catch clause already catches all exceptions of this or of a super type ('Exception').
So that to avoid compile time errors, we have to set the order of different exception catch blocks.

Wednesday, 26 July 2017

How To Bind The Data To List And Get The Data From List In C#

In this article i would like to know you about how the data should be bind to list and get the data from the List using c# code

Friday, 21 July 2017

To Remove First character in C#


using System;

namespace DateTimeSpanExample
{
    public class Program
    {
        public void Main(string[] args)
        {           
            string removeFirst = "/examples/csharp/";
            //using remove method
            var rf=removeFirst.Remove(0, 1);
            Console.WriteLine(rf);
            //using trimstart
            var ts=removeFirst.TrimStart('/');
            Console.WriteLine(ts);
            //using substring
            var ss=removeFirst.Substring(1);
            Console.WriteLine(ss);
            //using indexof
            var io=removeFirst.Remove(removeFirst.IndexOf("/"), 1);
            Console.WriteLine(io);
            Console.Read();
        }
    }
 

}

Optional Parameters In C#

Optional Parameters:-
1 1)      Optional Parameters should be given at last of all parameters.
2 2)      More than one optional parameter is also allowed, but should be at last.
3 3)      The definition of the optional parameter is as :

public async Task<IHttpActionResult> GetOptionalParams(string param1, string param2 = "",string param3="")
        {
               // some await code
                   return Ok();

  }

Convert DateTime In To Seconds Format And MilliSeconds Format And Vice Verse

The Conversion of DateTime format in to seconds is called Unix Timestamp
The Timestamp count starts from DateTime Of 1970-1-1 00:00:00, which is called Unix Epoch.

using System;

namespace UnixAndJavaTimeStampFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            //Previous datetime based on Current datetime
            int limittime = 10;
            DateTime currentdatetime = DateTime.Now;
            DateTime beforeDateTime = currentdatetime.AddDays(-limittime);  // Substract days based on given limit, if minus(-) is given, otherwise it Adds no. of Days
            // DateTime beforeDateTime = currentdatetime.AddMinutes(-limittime);

            /// for seconds
            DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            long unixTimestamp= (long)(beforeDateTime - sTime).TotalSeconds;
            Console.WriteLine("Unix Timestamp Format In Seconds : " + unixTimestamp);
            double timestamp = unixTimestamp;
            DateTime dateTimeformat = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            dateTimeformat = dateTimeformat.AddSeconds(timestamp);
            Console.WriteLine("Date Time Format For Seconds : "+ dateTimeformat);

            /// for milliseconds
            double unixTimestampmilliseconds = (long)(beforeDateTime - sTime).TotalMilliseconds;
            Console.WriteLine("Unix Timestamp Format In Milliseconds : " + unixTimestampmilliseconds);
            double milliTimestamp = unixTimestampmilliseconds;
            DateTime millidateTimeformat = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            millidateTimeformat = millidateTimeformat.AddMilliseconds(milliTimestamp);
            Console.WriteLine("Date Time Format for Milliseconds : " + millidateTimeformat);
            Console.ReadKey();
        }
    }

}

Friday, 7 July 2017

System.Collections.Generic.List'1[System.String]

I had used to store the List of items in object

i.e.,

var contactAddress = contact.AddressInformation.Where(x=>x.AddressInformation.AddressType.AddressTypeId==(int)contantEnumeration.AddressType.PrimaryAddress).Select(x=>x.AddressInformation.Address1).ToList();

In the above code, we are using to retrieve single data(element) from List of object and converting in to List by using .ToList(), so that it is unable o store single data(element) in to List,
So it is storing "System.Collections.Generic.List'1[System.String]".

I removed .ToList() from above code, then it is storing {System.Linq.Enumerable.WhereSelectEnumerableIterator<Application.Model.DataDomain.ContractAddress,String>}

Because the type conversion is not there and unable to store exact value to retrieve the single record data from the list.

So we have to use .FirstOrDefault() to view the expected data in the variable.

Overwriting the list of data with last data in the list of object

I am trying to add the object to the list of objects.

The below code I had written is :

                 Address adr=new Address();
List<Address> addr = new List<Address>();

foreach(var item in TransportAddress)
{
adr.Address1=item.Address1;
adr.Address2=item.Address2;
adr.PhoneNumber=item.PhoneNumber;

addr.Add(adr);
}


I the above code I had initialized the object  'adr' only once, so that it is overwritting the object data.

The code should be as below .


List<Address> addr = new List<Address>();

foreach(var item in TransportAddress)
{
                        Address adr=new Address();

adr.Address1=item.Address1;
adr.Address2=item.Address2;
adr.PhoneNumber=item.PhoneNumber;

addr.Add(adr);
}

Friday, 23 June 2017

Ananymous elements have same name in LINQ



This Exception came when  i try to query using LINQ to get the data in a variable as below :
var countryDetails = (from count in Supplier
                      where count.AddressInformation != null && count.AddressInformation.CountryInformation != null
                      select new
                      {
                          count.AddressInformation.CountryInformation.LongName,
                          count.AddressInformation.StateInformation.LongName

                      }).ToList();
To Resolve The Exception, We have to give Names to each variable in new object variable

i.e.,
var countryDetails = (from count in Supplier
                      where count.AddressInformation != null && count.AddressInformation.CountryInformation != null
                      select new
                      {
                          CountryName = count.AddressInformation.CountryInformation.LongName,
                          StateName = count.AddressInformation.StateInformation.LongName

                      }).ToList();

Saturday, 7 December 2013

Display PDF On Form Using Adobe PDF Reader In C#

Right Click On Toolbox 'Data' Controls And In The Displayed Pop-up Click On 'Choose Items...' As Shown Below:

Now 'Choose Toolbox Items' Dialog Box Will Displayed


In The 'Choose Toolbox Items' Select 'COM Components' Tab And Tick The Checkbox Of 'Adobe PDF Reader' And Click On 'Ok' Button.


In Toolbox 'Data' Controls 'Adobe PDF Reader' Is Added And Click The 'Adobe PDF Reader' And Place It On Form1 As Shown Below:


Now Place A Button On The Form And Named It 'btnShow'  As Shown Below:


Now Write The Below Code In Form1.cs

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;

namespaceShowPDFFileInAdobeReader
{
    public partial class Form1 : Form
    {
        publicForm1()
        {
            InitializeComponent();
        }
       
        privatevoid btnShow_Click(objectsender, EventArgs e)
        {
            stringpath1 = "C:\\ShowPDFFileInAdobeReader\\RamachandraExceptions.pdf";
          
           
           axAcroPDF1.src = path1;

            /* or  */

           /* string path1 = "..\\RamachandraExceptions.pdf";  //Path Should Be Given Like This If The PDF File Is Beside The Debug Folder And In The Bin Folder Of The Project
            axAcroPDF1.LoadFile(path1);     */


        }
       

    }
}

Note :-

If axAcroPDF1.LoadFile(path1); Path Should Be Given as string path1 = "..\\01Ashwini.pdf"//If The PDF File Is Beside The Debug Folder(In Which EXE File Exists) And In The Bin Folder Of The Project As Shown Below : 





If axAcroPDF1.src = path1; Full Path Should Be Given as string path1 = "C:\\ShowPDFFileInAdobeReader\\RamachandraExceptions.pdf"


Now Run The Project And Click On The "Show" Button It Gives The Following Output:

Output:-


Friday, 6 December 2013

Simple Example To Send Data From One Form To Another Form In C#

Design Form1 And Form2 As Below Shown:



Now, Write Below The Code In Form1.cs :

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;

namespaceSendStringFromOneFormToAnotherForm
{
    public partial class Form1 : Form
    {
        publicForm1()
        {
            InitializeComponent();
        }

        privatevoid button1_Click(objectsender, EventArgs e)
        {
            Form2frm2 = new Form2(textBox1.Text);
            frm2.Show();
        }
    }

}

Now, Write The Below Code In Form2.cs :

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;

namespaceSendStringFromOneFormToAnotherForm
{
    public partial class Form2 : Form
    {
        publicForm2(string str)
        {
            InitializeComponent();
            textBox1.Text = str;
        }
    }
}

Now, Run The Application And Give Any Text In The TextBox And Click On "Show Data In Other Form" Button, Then It Shows The Output As Below :

Output:-


Saturday, 3 August 2013

Add Items To Combobox In C# Winforms


using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;

namespace AddItemsToComboBox
{
    public partial class Form1 : Form
    {
        publicForm1()
        {
            InitializeComponent();
        }

        privatevoid Form1_Load(objectsender, EventArgs e)
        {
            // It Shows The Text On The Combobox On Form Load
            comboBox1.Text = "-Select-";

            //Below Code Shows The Combobox Items Added
            comboBox1.Items.Add("Ramachandra");
            comboBox1.Items.Add("Venkatesh");
            comboBox1.Items.Add("Shakti");
            comboBox1.Items.Add("Kranthi");
            comboBox1.Items.Add("Kasani");
        }
    }
}

Output:-