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

Sunday, June 14, 2020

C# Interview questions

What is serialization?
When transport an object through a network, then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization.
Deserialization is the reverse process of creating an object from a stream of bytes.
Can we use "this" command within a static method?
We can't use 'This' in a static method because we can only use static variables/methods in a static method.
What is the difference between constants and read-only?
Constant variables are declared and initialized at compile time. The value can't be changed afterward. Read-only is used only when we want to assign the value at run time.
What are sealed classes ?
We create sealed classes when we want to restrict the class to be inherited. Sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as base class, then a compile-time error occurs.
What is an object pool in .NET?
An object pool is a container having objects ready to be used. It tracks the object that is currently in use, total number of objects in the pool. This reduces the overhead of creating and re-creating objects.
Object Pooling allows objects to keep in the memory pool so the objects can be reused without recreating them.
Use the Factory pattern for this purpose. which will take care of the creation of objects.If there is any object available within the allowed limit, it will return the object, otherwise, a new object will be created and give you back.
What are delegates in C# and the uses of delegates?
Is an abstraction of one or more function pointers 
You can treat a function as data. 
It allow functions to be passed as parameters.
Why Do We Need Delegates?
Callback is to handle button-clicking.
is a solution for situations in which you want to pass methods around to other methods.
You do not know at compile time what this second method is. That information is available only at runtime, hence Delegates are the device to overcome such complications.
What is a Virtual Method in C#?
A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class.
The overriding method also provides more than one form for a method. Hence, it is also an example of polymorphism.



Friday, June 1, 2018

Dowload Attachment From Google Mail using IMAP


//POP is temporary only, so use IMAP better
//Nuget S22.IMAP

using (ImapClient client = new ImapClient("imap.gmail.com", 993, "Email", "App Password", AuthMethod.Login, true))
{
    IEnumerable<uint> uids = client.Search(
         SearchCondition.From("from@mail")
         .And(SearchCondition.SentSince(new DateTime(2018, 05, 01)))
          .And(SearchCondition.SentBefore(new DateTime(2018, 06, 01))), "Mail box Name");

    Console.WriteLine(uids.Count() + " Emails:");

    foreach (var uid in uids)
    {
        MailMessage message = client.GetMessage(uid,mailbox:"Mail box Name");

        Console.WriteLine(message.Subject);

        foreach (Attachment attachment in message.Attachments)
        {
            byte[] allBytes = new byte[attachment.ContentStream.Length];
            int bytesRead = attachment.ContentStream.Read(allBytes, 0, (int)attachment.ContentStream.Length);
            string destinationFile = @"C:\\myfile\\" + attachment.Name;
            BinaryWriter writer = new BinaryWriter(new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None));
            writer.Write(allBytes);
            writer.Close();
        }
   }
}

Monday, September 25, 2017

Condition Throw Exception

if (list == null || list.Count < 1)

    throw new ApplicationException("Get list Failed.");

Monday, January 9, 2017

Dictionary

static readonly Dictionary<string, DeviceType> MappedDeviceType;

static fnMapDeviceType()
{
    MappedDeviceType = new Dictionary<string, DeviceType>();
    MappedDeviceType.Add("Windows NT 6.3", DeviceType.Windows);
    MappedDeviceType.Add("Windows NT 6.3; WOW64", DeviceType.Windows);
    MappedDeviceType.Add("Windows NT 10.0", DeviceType.Windows);
    MappedDeviceType.Add("Windows NT 10.0; WOW64", DeviceType.Windows);
    MappedDeviceType.Add("CPU iPhone OS 9_3_2 like Mac OS X", DeviceType.Iphone);
}

//Mapping Method
public static DeviceType MapDeviceType(string device)
{
    DeviceType mapValue = DeviceType.Unknown;

    if (!string.IsNullOrWhiteSpace(device))
    {

        if (Enum.TryParse(device, true, out mapValue))
            return mapValue;

        if (MappedDeviceType.TryGetValue(device, out mapValue))
            return mapValue;
    }
    return mapValue;

}

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

//Contain en with key

   string word = "en/my";

            var mappingA = new Dictionary<string, string>()
            {
                { "en", "en-gb" },
                { "cn", "cn-zh" },
            };


string listPerson = mappingA.Where(x => word.Contains(x.Key)).Select(y => y.Value).FirstOrDefault();



Monday, August 15, 2016

Stream

Stream
is an abstract class that transfer bytes (read, write, etc.) to the source. 
It is like a wrapper class to transfer bytes. 
Classes that need to read/write bytes from a particular source must implement the Stream class.

FileStream
reads or writes bytes from/to a physical file whether it is a .txt, .exe, .jpg or any other file.

MemoryStream
reads or writes bytes that are stored in memory.

BufferedStream
reads or writes bytes from other Streams to improve the performance of certain I/O operations.

NetworkStream
reads or writes bytes from a network socket.

PipeStream
reads or writes bytes from different processes.

CryptoStream
is for linking data streams to cryptographic transformations.


FileStream writes bytes, StreamWriter writes text

Readers and Writers:

StreamReader
is a helper class for reading characters from a Stream by converting bytes into characters using an encoded value. It can be used to read strings (characters) from different Streams like FileStream, MemoryStream, etc.

StreamWriter
is a helper class for writing a string to a Stream by converting characters into bytes. It can be used to write strings to different Streams such as FileStream, MemoryStream, etc.

BinaryReader
is a helper class for reading primitive datatype from bytes.

BinaryWriter
writes primitive types in binary.

Immutable C#

String is immutable 
  • Once created, it cannot be changed. 
  • Each method of string is returns a new string instead of altering the original.
  • You can re-reference the back to original to get back the new string.
  • Thread safe
  • Low Perfomance when continuous change of value.
StringBuilder is mutable 
  • Efficient way to repeatedly append of string.

int i = 1;
int newI = i;
newI = 2;

Console.WriteLine("Old int :" + i);
Console.WriteLine("New int :" + newI);

Console.WriteLine("====================");

string str = "mystring";
string newString = str;
string newString2 = str.Replace('s', 'o');
newString = "asd";

Console.WriteLine("Old String :" + str);
Console.WriteLine("New String :" + newString);
Console.WriteLine("New String 2:" + newString2);

Console.WriteLine("==================");

MyClass myClass = new MyClass { myString = "TestString", myInt = 1 };
MyClass newMyClass = myClass;
newMyClass.myString = "Test";
newMyClass.myInt = 2;

Console.WriteLine("Old Object String :" + myClass.myString + "|Old Class Int :"+ myClass.myInt);
Console.WriteLine("New Object String :" + newMyClass.myString + "|Old Class Int :" + newMyClass.myInt);

--------------Result ----------------------
Old int : 1 //Value Type, so no change
New int : 2
====================
Old String : mystring   //immutable string , so no change
New String : asd
New String 2: myotring
==================
Old Object String : Test|Old Class Int :2 //object & object inside value type is reference type, so will change
New Object String : Test|Old Class Int :2  

Wednesday, August 10, 2016

Lamda Expression

Lambda expression is an anonymous function that you can use to create delegates or expression tree types

Func<double, double> cpointer = x => x * 3.123; //Input and Output
Action<string> action = y => Console.WriteLine(y); //Void
Predicate<int> GreaterThanFive = z => z > 5; //Input and Always return Bool

double area = cpointer(2);
action("action display");
bool isGreater = GreaterThanFive(4);

BinaryExpression b1 = Expression.MakeBinary(ExpressionType.Add, Expression.Constant(10), Expression.Constant(20));
BinaryExpression b2 = Expression.MakeBinary(ExpressionType.Add, Expression.Constant(5), Expression.Constant(3));
BinaryExpression b3 = Expression.MakeBinary(ExpressionType.Subtract, b1, b2);

int result = Expression.Lambda<Func<int>>(b3).Compile()();

== vs Equal

Return Bool

when 2 are objects
== compare 2 object is it pointing to same reference
Equal compare with Content

when 2 are string
== and Equal always compare as Content

Global Assembly Cache

Assemblies
  • A collection of single-file or multiple files (exe or dll), generate when compile successfully.
  • It can create application without disturb other (different version).
  • Composed by manifest, type metadata, MSIL, resources.
  • Strong name assemblies will have public key token.
  • Shared assemblies is GAC, and Private assemblies
Manifest 
  • Contain identification information.
  • Version, Name, Culture, Security Requirements.
GAC
  • Shared Assemblies at 1 location for all multiple .NET application.
  • Using GAC, we no need copy local physical file to every projects, it like system assembly(using System;)
  • It not suitable to xcopy deployment.
  • Why Imporant (Shared Location, Mutiple Versioning, File Security)
Step 1: Generate public key token
sn.exe -k c:\MyStrongKeys.snk (Developer Command Prompt)

Step 2: Add the Strong Key to Class library AssemblyInfo (Class > Properties > AssemblyInfo)
[assembly: AssemblyKeyFile("C:\\MyStrongKeys.snk")]

Step 3: Add the assembly to GAC
cd C:\Users\oby\Documents\visual studio 2015\Projects\Training\GACClassLibrary\bin\Debug
gacutil.exe -i GACClassLibrary.dll

.NET 4.0 > will at C:\Windows\Microsoft.NET\assembly\GAC_MSIL
.NET 4.0 < will at C:\Windows\assembly

Step 4: How to Call GAC

Specific Version and Key in code
Assembly SampleAssembly1 = Assembly.Load("GACClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30e23367dbe9711c");          

Specific Version and Key in WebConfig
Assembly SampleAssembly1 = Assembly.Load("GACClassLibrary");

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="GACClassLibrary" publicKeyToken="30e23367dbe9711c" Culture="neutral" />
        <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

Excecute It
 MethodInfo methodInfo1 = SampleAssembly1.GetTypes()[0].GetMethod("Main");



Strong and Weak Reference Assembly

Weak Reference is where the .exe file identifying the .dll files by namespace name and class name only.

Strong Reference is where the .exe file identifying the .dll files not only by namespace name and class name only, but also by a strong name.

Strong name is a unique name which is produced by the combination of version no, culture information, public key and digital signature.

Object-Oriented Programming vs Procedural Programming

Procedural programming
  • uses a list of instructions to tell the computer what to do step-by-step
  • relies on - you guessed it - procedures, also known as routines or subroutines.
  • Top-down languages.
  • Intuitive in the sense that it is similar to how you would expect a program to work. If you want a computer to do something, you should provide step-by-step instructions on how to do it. 
  • Most of the early programming languages are all procedural. Examples of procedural languages include Fortran, COBOL and C, around since the 1960s and 70s.
Object-Oriented Programming
  • is an approach to problem-solving where all computations are carried out using objects
  • An object is a component of a program that knows how to perform certain actions and how to interact with other elements of the program. 
  • A simple example of an object would be a person. name is a property of the person. Walking i s a method of the person.
  • Examples of object-oriented languages include C#, Java, Perl and Python.

POP
OOP
Divided Into
program is divided into small parts called functions.
program is divided into parts called objects.
Importance
Importance is not given to data but to functions as well as sequence of actions to be done.
Importance is given to the data rather than procedures or functions because it works as a real world.
Approach
Top Down approach.
Bottom Up approach.
Access Specifiers
does not have any access specifier.
has access specifiers named Public, Private, Protected, etc.
Data Moving
Data can move freely from function to function in the system.
 objects can move and communicate with each other through member functions.
Expansion
To add new data and function is not so easy.
provides an easy way to add new data and function.
Data Access
 function uses Global data for sharing that can be accessed freely from function to function in the system.
data cannot move easily from function to function, it can be kept public or private so we can control the access of data.
Data Hiding
does not have any proper way for hiding data so it is less secure.
provides Data Hiding so provides more security.
Overloading
Overloading is not possible.
overloading is possible in the form of Function Overloading and Operator Overloading.
Examples
Example of POP are : C, VB, FORTRAN, Pascal.
Example of OOP are : C++, JAVA, VB.NET, C#.NET.