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

Custom Attributes in C#

Attributes are using to add information to Metadata. DotNet provides two types of attributes one is Custom and other is Pre-defined. The pre-defined Attribute AttributeUsage will help us to create new Attributes for classes .It contain few parameters like.

ValidON: Means which attributes can be placed. There is an enumeration for this, Default value is AttributeTargets.All.
AllowMultiple: This is used for activating multiple creation of the property. Default is single use.
Inherited: The parameter inherited (optional) provides value for the Inherited.

 The .Net Framework allows creation of custom attributes that can be used to store declarative information and can be retrieved at run-time. The below example helps to add the QC fix information’s to all methods, classes..
    [AttributeUsage(AttributeTargets.Class |
    AttributeTargets.Constructor |
    AttributeTargets.Field |
    AttributeTargets.Method |
    AttributeTargets.Property,
    AllowMultiple = true)]
    public class FixInfo : System.Attribute
    {
        private string qcNo;
        private string name_ofOwnr;
        private string dateofChage;
        public string description;
        public FixInfo(string bg, string dev, string d)
        {
            this.qcNo = bg;
            this.name_ofOwnr = dev;
            this.dateofChage = d;
        }
        public string QCNo
        {
            get
            {
                return qcNo;
            }
        }
        public string Owner
        {
            get
            {
                return name_ofOwnr;
            }
        }
        public string Date
        {
            get
            {
                return dateofChage;
            }
        }
        public string Description
        {
            get
            {
                return description;
            }
            set
            {
                description = value;
            }
        }
    }
}

The implementation of this Attribute like this.
[FixInfo("QCXXX1","Santhosh","01/12/2014", "Added additional Condition")]
[FixInfo("QCXX81", "Santhosh", "20/12/2014", "NUll value condition check added")]
        public void getmarks()
        {
            //.............
            ///Yourlogic
            /////...................
        }

 Happy doing....

Converting a list to string

Many of requirement's wants to convert list of string to a coma separated or any other format . We all are mostly followed Looping through & get it. Here is the simple example for doing that.

For Converting a list string to string


List<string> lststr = new List<string>();

lststr.Add("Hello") ;
lststr.Add("good");
lststr.Add("Morning");


string concate = string.Join<string>(",", lststr);

For Converting A list of classes We can use the below snippet.


class Data
{
   public int ID { get; set; }
   public string Name { get; set; }
}

List<Data> ldata = new List<Data>();
           
Data dt=new Data();
dt.ID=1;
dt.Name="San";
ldata.Add(dt);

dt=new Data();
dt.ID=2;
dt.Name="Kumar";
ldata.Add(dt);

string FullName = string.Join<string>(",", ldata.Select(x => x.Name));

Happy Doing...:)

Auto-Property Initializers in C# 6.0

An Atomic property is an advantage of Property hiding from out side world. It will reduce the Declareation space.There one difficulty we faced while initilizing a property in the loading time itself.
This behavior is then repeated for all properties on the type. So doing the right thing requires significantly more effort than the brittle approach. It will be more help full for getting C# 6.0 comes to the rescue with a new feature called auto-property initializers . The auto-property initializer allows assignment of properties directly within their declaration. For read-only properties, it takes care of all the ceremony required to ensure the property is immutable. Consider, for example, the DoublePrint class in this example:

 Implementation

 public class DoublePrint
{


  public DateTime TimeStamp { get; } = DateTime.UtcNow;

 public string User { get; } = System.Security.Principal.WindowsPrincipal.Current.Identity.Name;

 public string Process { get; } =System.Diagnostics.Process.GetCurrentProcess().ProcessName;

}



----------------------------------Happy to doing....

String Intern method.

The common language runtime automatically maintains a table, called the intern pool, which contains a single instance of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically by calling the Intern method.
The intern pool conserves string storage. If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.
This method looks up str in the intern pool. If str has already been interned, a reference to that instance is returned; otherwise, null is returned.
Compare this method to the Intern method.
This method does not return a Boolean value. If you call the method because you want a Boolean value that indicates whether a particular string is interned, you can use code such as the following.

     string str1 = "test"; //
            string str2 = str1 + "1 test 1"; //
            string str3 = str2 + "2 test 2"; //
            string[] strings = { "value", "part1" + "_" + "part2", str3, 
                           String.Empty, null };
            foreach (var value in strings)
            {
                if (value == null) continue;
                bool interned = String.IsInterned(value) != null;
                if (interned)
                    Console.WriteLine("{0} is in the string intern pool.",
                                      value);
                else
                    Console.WriteLine("{0} is not in the string intern pool.",
                                      value);
            }
            // ----------------
            // Output is
            // First & Second array will be interned ('Value' , 'part1_part2')
            //but str3 is not a interned value.
 
            String str = "abcd";
            String isInterned = String.IsInterned(str);
            if (isInterned == null)
                Console.WriteLine("{0}', is not interned.", str);
            else
                Console.WriteLine("{0}', is interned.", isInterned); 
            //abcd is interned
            str = new StringBuilder().Append("AD").Append("BC").ToString();
            isInterned = String.IsInterned(str);
            if (isInterned == null)
                Console.WriteLine("{0}', is not interned.", str);
            else
                Console.WriteLine("{0}', is interned.", isInterned);
            // here ABCD is no an interned
            Console.Read();

Happy doing.....

CDATA in XML & Read it using C#

CDATA is used for saving/storing unparced character data.Whatevrr data which we given in CDATA section which will eleminate by XML Parser. CDATA is usefull for storing the HTML,Javascript,XAML data. CDATA is used about text data that should not be parsed by the XML parser. Characters like "<" and "&" are illegal in XML elements."<" will generate an error because the parser interprets it as the start of a new element."&" will generate an error because the parser interprets it as the start of an character entity.
A CDATA section starts with "<![CDATA[" and ends with "]]>":

CDATA STORIng example.

  <EmailTemplate>
    <Template name="PaymentCreate">
      <![CDATA[<div style=' border:solid 1px #99FFFF' runat='server'><div style='background-color:#95aa77'>
    <p style='margin:0in;font-size:17.0pt;>
    <span style='font-weight:bold;font-family: Courier New CE'>Dear #UserName#</span></p><p style='margin:0in;font-family:Times New Roman;font-size:11.0pt'>#DateTime#</p>
    </div>
    <div style='border:solid 1px #c3c3c3;background-color:#CCFFFF'></br><p style='margin:0in;font-family:Times New Roman;font-size:14.0pt;color:#993300;'>
    <span style='font-weight:bold;font-family: Courier New CE'>Your Payment Voucher has been generated for Month of #Month# Year #Year#.</span></p>
    <p style='margin:0in;font-family:Times New Roman;font-size:14.0pt;color:#993300'></p>
    <p style='margin:0in;font-family:&quot;Times New Roman&quot;font-size:9.5pt;color:#2E75B5'>
    </br><span style='font-weight:bold;font-family: Courier New CE'>Amount<span style='mso-spacerun:yes'></span>:<span style='color:red;'> #Amount#</span></span></p>
    <p style='margin:0in;font-family:&quot;Times New Roman&quot;font-size:9.5pt;color:#2E75B5'>
    <span style='font-weight:bold;font-family: Courier New CE'>Last Date<span style='mso-spacerun:yes'></span>:<span style='color:red;'>#LastDate#</span>
    <span style='mso-spacerun:yes'></span></span></p><p style='margin:0in;font-family:&quot;Times New Roman&quot;font-size:9.5pt;color:#2E75B5'>
    <span style='font-weight:bold;font-family: Courier New CE'>Your E-Collections Account number : #AccountNumber#</span></p>
    <p style='margin:0in;font-family:Times New Roman;font-size:14.0pt;color:#993300'>&nbsp;</p></div>
    <div style='background-color:#95aa77'>
    <p style='margin:0in;font-family:Times New Roman;font-size:11.0pt;color:#375623'>
    <span style='font-weight: bold; '>The Owners’ Association</span></p>
    <p style='margin:0in;font-size:11.0pt'><span style='font-weight: bold; font-family: Times New Roman; color: #375623; '>Reg No</span>
    <span style='font-family: Century; color: #538135; '>:126/2013</span></p><p style='margin:0in;font-size:11.0pt'>
    <span style='font-family: Times New Roman; '>OMR Road </span><span style='font-family: Calibri; '> Kalavakkam</span>
    <span style='font-family: '>-</span><span style='font-family: Calibri; '>Tiruporur</span><span style='font-family:  '>-</span><span style='font-family: Calibri; '>Chennai</span><span style='font-family:  '>-</span><span style='font-family: Calibri; '>Tamil Nadu</span><span style='font-family: '>-</span><span style='font-family: Calibri; '>PIN: 603110 </span></p><p style='margin:0in;font-family:Times New Roman;font-size:11.0pt'><span style='font-weight: bold; color: #375623; '>Phone</span><span>: +91-0000000000 </span> </p><p style='margin:0in;font-family:Times New Roman;font-size:11.0pt'><span style='font-weight: bold; color: #375623; '>E-Mail</span><span style=''>: </span></p><p style='margin:0in;font-family:Times New Roman;font-size:11.0pt'><span style='font-weight: bold; color: #375623; '>WebSite</span><span style=''>:www.google.com</span></p></div></div>]]>
    </Template>
  </EmailTemplate>

We can read the CDATA using C#:

XElement XTemp = XElement.Load("EmailTemplate.xml");
                var queryCDATAXML = from element in XTemp.DescendantNodes()
                                    where element.NodeType == System.Xml.XmlNodeType.CDATA
                                    select element.Parent.Value.Trim();
                string BodyHtml = queryCDATAXML.ToList<string>()[0].ToString(); 

The above code will used for reading thae above CDATA. You can save the xml in your System and use the code.This will be usefull for storing templates in HTML,WPF & Silverlight .Also we can use this for storing functions like javascript....

Happy Doing.......

 

Dependency Injection Principal (DIP)

Dependency injection Principal ensures it should be more and perfect abstraction between base level & derived level implementation. Dependency inversion principle is to decouple application glue code from application logic. Reusing low-level components (application logic) becomes easier and maintainability is increased.        

 The below example is all about Project management in normal it field. Based on requirement we will add junior developers and senior developers.Here the manager manage only one junior developer & one senior developer .In future s/he needs to add one more junior then it is easy to create a new collection of developers with IEngineer.
/// <summary>
    /// Interface for Developer people
    /// </summary>
    public interface IEngineer
    {
        void Dowork();
    }
    /// <summary>
    /// Interface for Mentoring people
    /// </summary>
    public interface IMentor
    {
        void DoMentoring();
    }
 
    /// <summary>
    /// Class implementing Developer qualities
    /// </summary>
    public class SoftwareEngineer : IEngineer
    {
        public string Name { get; set; }
 
        public void Dowork()
        {
            Console.WriteLine(Name + " Doing Coding....");
        }
    }
    /// <summary>
    /// Class implementing Developer & Mentor Qualities
    /// </summary>
    public class SeniorSoftwareEngineer : IEngineer, IMentor
    {
        public string Name { get; set; }
 
        public void DoMentoring()
        {
            Console.WriteLine(Name +  " Mentoring Juniors...");
        }
 
        public void Dowork()
        {
            Console.WriteLine(Name +  " Doing Coding....");
        }
    }
    /// <summary>
    /// Manager class for Managing .With the implementation of Developers & Mentors
    /// </summary>
    public class Manager
    {
        IEngineer Developers;
        IMentor Mentors;
 
        public void SetWorker(IEngineer developer)
        {
            Developers = developer;
        }
 
        public void SetMenter(IMentor mentor)
        {
            Mentors = mentor;
        }
 
        public void Manage()
        {
            if(Developers !=null)
            Developers.Dowork();
 
            if(Mentors !=null)
            Mentors.DoMentoring();
        }
    }
 
Call
Manager manager = new Manager();
SoftwareEngineer Sharan = new SoftwareEngineer { Name = "Sharan" };
SeniorSoftwareEngineer Jannet = new SeniorSoftwareEngineer { Name = "Jannet" };
 
            manager.SetWorker(Sharan);
            manager.Manage();
 
            manager.SetWorker(Jannet);
            manager.SetMenter(Jannet);
            manager.Manage();
 
dd