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

Saturday, 15 January 2022

 

1) What is Access modifiers in C# ?

Access modifiers are  used to specify the scope of accessibility of a member of a class or type of the class itself. For example, a public class is accessible to everyone without any restrictions, while an internal class may be accessible to the containing assembly only.

Types : 

Private: limits the accessibility of a member to within the defined type, for example if a variable or a functions is being created in a ClassA and declared as private then another ClassB can't access that.

Public: has no limits, any members or types defined as public can be accessed within the class, assembly even outside the assembly. Most DLLs are known to be produced by public class and members written in a .cs file.

Internal: internal plays an important role when you want your class members to be accessible within the assembly. An assembly is the produced .dll or .exe from your .NET Language code (C#). Hence, if you have a C# project that has ClassA, ClassB and ClassC then any internal type and members will become accessible across the classes with in the assembly.

Protected:
 plays a role only when inheritance is used. In other words any protected type or member becomes accessible when a child is inherited by the parent. In other cases (when no inheritance) protected members and types are not visible.

Protected internal:
 is a combination of protected and internal both. A protected internal will be accessible within the assembly due to its internal flavor and also via inheritance due to its protected flavor.

Code :

1) Lets create a console c# application.
2) Create a new class file and add the code as below ,

class Class1
    {
        //Available only to the container Class 
        private string privateVariable;

        // Available in entire assembly across the classes 
        internal string internalVariable;

        //Available in the container class and the derived class   
        protected string protectedVariable;

        //Available to the container class, entire assembly and to outside    
        public string publicVariable;

        //Available to the derived class and entire assembly as well
        protected internal string protectedInternalVariable;

        private string PrivateFunction()
        {
            privateVariable = "";
            return privateVariable;
        }

        internal string InternalFunction()
        {
            privateVariable = "";
            internalVariable = "";
            return internalVariable;
        }

        protected string ProtectedFunction()
        {
            privateVariable = "";
            internalVariable = "";
            return protectedVariable;
        }

        public string PublicFunction()
        {
            privateVariable = "";
            internalVariable = "";
            return publicVariable;
        }

        protected internal string ProtectedInternalFunction()
        {
            privateVariable = "";
            internalVariable = "";
            return protectedInternalVariable;
        }
    }

3) Go to your program.cs file, In main method create object for your class and try to access the created fields with the object. 

You can see from below image only Internal, Protected Internal and public variable fields can be accessible.

Private is not shown due to its limited scope with in the class.

Protected members also not showing in below, because protected members can be accessed with derived class inheriting parent class.
 



Create a new Console Application project and create a class file, create a method in that class. Add reference of our above project to this project. Create a instance of Class1 of our previous project in this project method , You can see only public fields and methods can be accessible, if our above project class is private it cannot be accessed in this project. By default the access modifier of class is Internal  and private for class members.



Inherit from Class1 of that project to this project class as below image,



You can see in test1 method, we can able to see protected , protected Internal and public methods and fields with this keyword after inheriting from parent cclass in that project.

Internal will be accessed only with in assembly meaning with that  project dll or exe.

Wednesday, 4 July 2018

Consume authorized Web Api and return results into Datatable C#

try
            {
               
                string credentials = String.Format("{0}:{1}", "usernameValues", "PasswordValues");
                // real key!!!!
                byte[] bytes = Encoding.ASCII.GetBytes(credentials);
                string base64 = Convert.ToBase64String(bytes);
                string authorization = String.Concat("Basic ", base64);

                HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create("YOUR WebApi URL");
                GETRequest.Method = "GET";
                GETRequest.Headers.Add("authorization", authorization);
                GETRequest.Timeout = 200000;
                GETRequest.Accept = "application/json";
                GETRequest.ContentType="application/json";
                GETRequest.UseDefaultCredentials = true;
                GETRequest.PreAuthenticate = true;
                GETRequest.Credentials = CredentialCache.DefaultCredentials;

                HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
                Stream GETResponseStream = GETResponse.GetResponseStream();
                StreamReader sr = new StreamReader(GETResponseStream);
                string jsonString = sr.ReadToEnd();
                DataTable dt = JsonStringToDataTable(jsonString.Replace("\n", "").Replace("null", string.Empty));
              }
            catch (WebException webex)
            {

              }

public DataTable JsonStringToDataTable(string jsonString)
    {
        DataTable dt = new DataTable();
        string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
        List<string> ColumnsName = new List<string>();
        foreach (string jSA in jsonStringArray)
        {
            string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
            foreach (string ColumnsNameData in jsonStringData)
            {
                try
                {
                    int idx = ColumnsNameData.IndexOf(":");
                    string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
                    if (!ColumnsName.Contains(ColumnsNameString))
                    {
                        ColumnsName.Add(ColumnsNameString);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
                }
            }
            break;
        }
        foreach (string AddColumnName in ColumnsName)
        {
            dt.Columns.Add(AddColumnName.Trim());
        }
        foreach (string jSA in jsonStringArray)
        {
            string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
            DataRow nr = dt.NewRow();
            foreach (string rowData in RowData)
            {
                try
                {
                    int idx = rowData.IndexOf(":");
                    string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "").Trim();
                    string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");

                    nr[RowColumns] = RowDataString.Trim();

                }
                catch (Exception ex)
                {
                    continue;
                }
            }

            dt.Rows.Add(nr);
            //foreach (DataRow dr in dt.Rows) // search whole table
            //{
            //    if (dr["MANUAL_ADJUSTMENT"].ToString() == string.Empty) // if id==2
            //    {
            //        dr["MANUAL_ADJUSTMENT"] = "0.0000"; //change the name
            //        //break; break or not depending on you
            //    }
            //}
        }

        return dt;
    }

Thursday, 5 February 2015

Creating a New file without replacing existing file using IO Streams CreateNew

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Streams1
{
    class Program
    {
        static void Main(string[] args)
        {        
            string str = "H:\\yourfilename.doc";
            string str1 = "H:\\yourfilename";
            string str2 =".doc";
            //FileStream fs1 = new FileStream(str);
            int i = 0;
            while (File.Exists(str))
            {
                i++;
                str = str1 + i.ToString() + str2 ;
            }
            FileStream fs = new FileStream(str, FileMode.CreateNew, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            Console.WriteLine("wirte some datas into the str:");
            string str3 = Console.ReadLine();
            sw.Write(str3);
            sw.Flush();
            sw.Close();
            Console.ReadLine();
        }

    }
}

Friday, 23 January 2015

C# Understanding Write and WriteLine()


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WriteandWriteLine
{
    class Program
    {
        static void Main(string[] args)
        { 
            Console.Write("ONE"); // THIS PRINTS ONE
            Console.Write(" TWO"); // THIS PRINTS TWO IN SAME LINE.
            Console.WriteLine(" THREE");// THIS WOULD HAVE PRINTED IN NEWLINE IF WE COMMENT OUT TOP TWO WRITE.
            Console.WriteLine("FOUR"); // THIS PRINTS IN NEWLINE
            Console.WriteLine("FIVE");  // THIS PRINTS IN NEWLINE
            Console.ReadLine(); // Console.ReadLine(); is to keep focus the window
        }
    }
}



C# Basic Program - Understanding For Loop


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace For_five
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("--- For 1 ---");
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine(i);
            }

             Console.WriteLine("--- For 2 ---");
            for (int i = 10 - 1; i >= 0; i--)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine();

            Console.WriteLine("--- For 3 ---");
            for (int i = 0; i < 10; i += 2)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine();

            Console.WriteLine("--- For 4 ---");
            for (int i = 10 - 1; i >= 0; i -= 2)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine();

            Console.WriteLine("--- For 5 ---");
            for (int i = 0; i < (20 / 2); i += 2)
            {
                Console.WriteLine(i);
            }

            Console.ReadLine();
        }
        
    }
}



C # Basic Programs to print a line using various methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharptestapplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Box");
            Console.Write("Table");
            Console.Write("chair");
            Console.WriteLine();
            Console.WriteLine("desk");
          //  Console.ReadLine();
            //Console.ReadKey();
           // Console.Read();
        }
    }
}

-----------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test3
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.test();
        }

        public static void test()
        {
            Console.WriteLine("hi World");
        }
    }
}

-----------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test4
{
    class Program
    {
        static void Main(string[] args)
        {
            a ob = new a();
            ob.test();
        }
    }

    class a
    {
        public void test()
        {
            Console.WriteLine("hi World");
        }
    }
}

-----------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test5
{
    class Program
    {
        static void Main(string[] args)
        {
            a.test();
        }
    }

    class a
    {
        public static void test()
        {
            Console.WriteLine("hi World");
        }
    }

}

-----------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test6
{
    class Program
    {
        static void Main(string[] args)
        {
            a ob1 = new a();
            ob1.test1();

            b ob2 = new b();
            ob2.test2();

        }
    }

    class a
    {
        public void test1()
        {
            Console.WriteLine("hi World 1");
        }
    }

    class b
    {
        public void test2()
        {
            Console.WriteLine("hi World 2");
        }
    }

}

-----------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test7
{
    class Program
    {
        static void Main(string[] args)
        {
            a ob = new a();
            ob.test1();
            ob.test2();
          
        }
    }

    class a
    {
        public void test1()
        {
            Console.WriteLine("hi World 1");
        }

        public void test2()
        {
            Console.WriteLine("hi World 2");
        }
    }
}
-----------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test8
{
    class Program
    {
        static void Main(string[] args)
        {
            b ob = new b();
            ob.test1();
            b.test2();
        }
    }

    class a
    {
        public void test1()
        {
            Console.WriteLine("hi world 1");
        }
    }

    class b:a
    {
        public static void test2()
        {
            Console.WriteLine("hi world 2");
        }
    }
}

-----------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test9
{
    class Program:a
    {
        static void Main(string[] args)
        {
            Program ob = new Program();
            ob.test1();
            ob.test2();
        }

        public void test2()
        {
            Console.WriteLine("hi world 1");
        }
    }

    class a
    {
        public void test1()
        {
            Console.WriteLine("hi world 2");
        }
    }
}