0% found this document useful (0 votes)
29 views42 pages

Level 2

The document covers advanced programming topics including exception handling, file operations, asynchronous programming, generics, reflection, serialization, delegates, and events in C#. It explains key concepts such as try-catch for error handling, various methods for reading and writing files, and the importance of asynchronous programming for responsive applications. Additionally, it discusses the use of generics for code reusability and type safety, as well as the role of delegates and events in event-driven programming.

Uploaded by

legendkiller5578
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views42 pages

Level 2

The document covers advanced programming topics including exception handling, file operations, asynchronous programming, generics, reflection, serialization, delegates, and events in C#. It explains key concepts such as try-catch for error handling, various methods for reading and writing files, and the importance of asynchronous programming for responsive applications. Additionally, it discusses the use of generics for code reusability and type safety, as well as the role of delegates and events in event-driven programming.

Uploaded by

legendkiller5578
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Level – 2

Advance Topic in Programming


1- Exception Handling
• Errors / invalid inputs / resources allocation failed all of those cases
refer to one concept which is the Exception

The Exception means my code executable and running in success way


but in special case of execution or when some inputs trying to entered
the system something went wrong in bad way it’s going to crush the
system execution stop debugging for the program .

Which this is not a good news


• On the other hand the main target of the programmer in whole world
is to build reliability system can run for as long as possible with out
any crushing or stopping the execution but it’s impossible except just
in one case because you can’t by default prevent the wrong input
and you don’t now when the database will receive more than the
maximum pool connection and you don’t know if the requested
folder or file is available or not on the device and you don’t know
either if the object is still available or has been deleted for all of those
cases we use special gun and we called them (try – catch ) our in
general the exception handling operator .
• Try statement allows you to define a block of code to be tested for
errors while it is being executed.
• Catch statement allows you to define a block of code to be executed,
if an error occurs in the try block.
try {
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
try
{
//Code
}
catch (Exception e)
{
//catch
}
finally
{
//finally
}
2- FILES
• In the past the concept of database but the programming concept is
exist and for daily use program we need to store data about customer
about user about operations , inputs , the execution result
• And all of the previous data collection saved data temporarily which
means when the program is stooped the data will lost and for
execution result storing the console screen just show the execution
result it’s will not save any line of even character .
• On the other hand I need to save the execution result then i will be
able to return this
• C# can provide many way to handle the working with file and provide
different choices to deal with file system
• But even of that now the file also important usage even with web API

1- Logging file
2- Generate reports
3- working with images and much more

And we will learn much more concept about it


Read Data From File
var fileName = @"C:\Users\Jano\Documents\words.txt";

using FileStream fs = File.OpenRead(fileName);

byte[] buf = new byte[1024];


int c;

while ((c = fs.Read(buf, 0, buf.Length)) > 0)


{
string name =Encoding.UTF8.GetString(buf, 0, c);
}
Read Second Way
var fileName = @"C:\Users\Jano\Documents\words.txt";

using FileStream fs = File.OpenRead(fileName);


using var sr = new StreamReader(fs);

string line;

while ((line = sr.ReadLine()) != null)


{
Console.WriteLine(line);
}
Write on File
var fileName = @"C:\Users\Jano\Documents\words.txt";

using FileStream fs = File.Create(fileName);


using var sr = new StreamWriter(fs);

sr.WriteLine("coin\nfalcon\nhawk\nforest");

Console.WriteLine("done");
Update / Add content to file

var fileName = @"C:\Users\Jano\Documents\words.txt";

File.AppendAllText(fileName, "Hamza bdair");


Over Ride On file
var fileName = @"C:\Desktop\studentMark.txt";
using var fileStream = File.OpenWrite(fileName);
using var sr2 = new StreamWriter(fileStream);
sr2.WriteLine("TestAdd,100");
Copy
var fileName = "words.txt";
using var fs = new FileStream(fileName, FileMode.Open);

var fileName2 = "words_copy.txt";


using var fs2 = new FileStream(fileName2, FileMode.OpenOrCreate);

fs.CopyTo(fs2);

Console.WriteLine("File copied");
3- Use Statement
• The using statement is used to set one or more than one
resource. These resources are executed and the resource is
released. The statement is also used with database operations.
• The main goal is to manage resources and release all the
resources automatically.

• Allow Resources inherit from the IDisposable interface. With the using
statement we ensure that the resources are correctly released
• The main goal is to allow the programmer to explicitly perform
these clean-up activities, objects can provide a Dispose
method that can be invoked when the object is no longer
needed. The C# using statement defines a boundary for the
object outside of which, the object is automatically
destroyed. The using statement in C# is exited when the end
of the "using" statement block or the execution exits the
"using" statement block indirectly, for example - an
exception is thrown
4- LINQ
• stands for Language Integrated Query
• Microsoft’s query language is fully integrated and offers easy data
access from in-memory objects, databases, XML documents, and
many more
• Prior to LINQ, it was essential to learn C#, SQL, and various APIs that
bind together the both to form a complete application. Since, these
data sources and programming languages face an impedance
mismatch; a need of short coding is felt.
• Because we use different data sources such as file , db , cloud we
have multiple database or using different database connection ways
we need to have something dynamic work with different data sources
in the same way .
Lamda Expression
• Lambda expressions in C# are used like anonymous functions, with
the difference that in Lambda expressions you don’t need to specify
the type of the value that you input thus making it more flexible to
use.
The ‘=>’ is the lambda operator which is used in all lambda
expressions. The Lambda expression is divided into two parts, the left
side is the input and the right is the expression.
input => { statements };
5- Asynchronous programming
• Asynchronous programming is a technique that enables your program
to start a potentially long-running task and still be able to be
responsive to other events while that task runs, rather than having to
wait until that task has finished. Once that task has finished, your
program is presented with the result.

• Many functions provided by browsers, especially the most interesting


ones, can potentially take a long time, and therefore, are
asynchronous
The Default (Synchronous programming )
• During the execution, an application gets blocked and
becomes unresponsive (You can see this in
Windows-based applications mainly). This is called
synchronous programming where execution does not go
to next line until the current line executed completely.
• Sample of this when we using Thread to hold system
just for some time then will continue

• System.Threading.Thread.Sleep(4000);
• On the other hand the async means the code gets executed in
a thread without having to wait for an I/O-bound or
long-running task to finish .
• Microsoft recommends Task-based Asynchronous
Pattern to implement asynchronous programming in
the .NET Framework or .NET Core applications
using async , await keywords
and Task or Task<TResult> class.
• It’s help us to work unparallel with our code
Thread
• thread is a single continuous flow of control within a program.
Multithreading is a technique where the processor uses multiple
threads to execute multiple processes concurrently.

• Multithreading is a programming technique for executing


operations running on multiple threads (also called workers)
where we use different threads and block them until the job is
done. Asynchronous programming is the concurrent execution of
multiple tasks (here the assigned thread is returned back to a
thread pool once the await keyword is reached in the method).

• We mainly use multithreading when we want to maximize the


multi-core processors to have multiple workers working
independently.
Thread vs Async
• Asynchronous programming is about the asynchronous
sequence of Tasks, while multithreading is about
multiple threads running in parallel.
• A thread can do many more useful things. Await is
specifically designed to deal with something taking time,
most typically an I/O request. Which traditionally was
done with a callback when the I/O request was
complete. Writing code that relies on these callbacks is
quite difficult, await greatly simplifies it.
6-Generic
• Generic means the general form, not specific. In C#, generic means
not specific to a particular data type.

• C# allows you to define generic classes, interfaces, abstract classes,


fields, methods, static methods, properties without the specific data
type.
• A type parameter is a placeholder for a particular type specified when
creating an instance of the generic type.
Data Class

class DataStore<T> {
public T Data { get; set;}
}

typeof(T)
Generic Class Characteristics
• A generic class increases the reusability. The more type
parameters mean more reusable it becomes. However,
too much generalization makes code difficult to
understand and maintain.
• A generic class can be a base class to other generic or
non-generic classes or abstract classes.
• A generic class can be derived from other generic or
non-generic interfaces, classes, or abstract classes.
Advantages of Generics

1. Generics increase the reusability of the code. You don't


need to write code to handle different data types.
2. Generics are type-safe. You get compile-time errors if
you try to use a different data type than the one
specified in the definition.
3. Generic has a performance advantage because it
removes the possibilities of boxing and unboxing.
7-Extensions and Helpers
• Extension Method

Extension methods, as the name suggests, are additional


methods. Extension methods allow you to inject
additional methods without modifying, deriving or
recompiling the original class, struct or interface.
Extension methods can be added to your own custom
class, .NET framework classes, or third party classes or
interfaces.
• An extension method is actually a special kind of static
method defined in a static class. To define an extension
method, first of all, define a static class.

namespace ExtensionMethods
{
public static class IntExtensions
{
public static bool IsGreaterThan(this int i, int value)
{
return i > value;
}
}
}
8-Reflection
• objects are used for obtaining type information at runtime. The
classes that give access to the metadata of a running program
are in the System.Reflection namespace.
• The System.Reflection namespace contains classes that allow
you to obtain information about the application and to
dynamically add types, values, and objects to the application
Applications of Reflection
• Reflection has the following applications −
• It allows view attribute information at runtime.
• It allows examining various types in an assembly and
instantiate these types.
• It allows late binding to methods and properties
• It allows creating new types at runtime and then performs
some tasks using those types.
First - way
• 1- get the path for dll file
2- create object from assembly class
3- create array of Type to get assembly Types
4- for each type you can get the classes inside project
5- for each class we can fetch the method
6- for each methods we can view the params
Second Way
1. Get type for built in class such as string loop through methods
2. For each methods get the type of parameter and it’s details
9-Serialization and Deserialization

• Serialization is the process of converting the state of an


object into a form (string, byte array, or stream) that can be
persisted or transported.
• Deserialization is the process of converting the serialized
stream of data into the original object state. This ensures
that the original state is not altered and is recreated when
we need it.
• Serialization is useful for the storage and exchange of object
states. Within the application memory, the state of an object
resides in complicated data structures which is unsuitable
for storage or exchange over the network.
With serialization, we can transfer objects:
• Between client and server via REST APIs or GRPC
• Over the network for messaging systems like Kafka
or RabbitMQ
• Through firewalls as JSON or XML strings
• To other data stores like SQL or NoSQL databases for
persistence
• Deserialization is typically useful in reconstructing the
object to its original state at its destination for further
processing.
Examples
1- Define the class that will be serialized
public class ClassToSerialize {
public int age = 100;
public string name = "bipin";
}
2- serialized
ClassToSerialize c = new ClassToSerialize();
File f = new File("temp.dat");
Stream s = f.Open(FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(s, c);
s.Close();
• 3- Deserialize

ClassToSerialize c = new ClassToSerialize();


File f = new File("temp.dat");
Stream s = f.Open(FileMode.Open);
BinaryFormatter b = new BinaryFormatter();
c = (ClassToSerialize)
b.Deserialize(s);
Console.WriteLine(c.name);
s.Close();
Delegates
• The delegate is a reference type data type that defines
the method signature. You can define variables of
delegate, just like other data type, that can refer to any
method with the same signature as the delegate.
• There are three steps involved while working with
delegates:
1. Declare a delegate
2. Set a target method
3. Invoke a delegate
Events
• An event is a notification sent by an object to signal the
occurrence of an action. Events in .NET follow
the observer design pattern.

• The class who raises events is called Publisher, and the


class who receives the notification is called Subscriber.
There can be multiple subscribers of a single event.
Typically, a publisher raises an event when some action
occurred. The subscribers, who are interested in getting
a notification when an action occurred, should register
with an event and handle it
Events
• In C#, an event is an encapsulated delegate. It is
dependent on the delegate. The delegate defines the
signature for the event handler method of the
subscriber class.
public delegate void Notify(); // delegate

public class ProcessBusinessLogic


{
public event Notify ProcessCompleted; // event

public void StartProcess()


{
Console.WriteLine("Process Started!");
// some code here..
OnProcessCompleted();
}

protected virtual void OnProcessCompleted() //protected virtual method


{
//if ProcessCompleted is not null then call delegate
ProcessCompleted?.Invoke();
}
}

You might also like