WPF Class Hierarchy

Dispatcher Object

WPF uses a single-threaded model it means the entire UI is owned by a single thread. So you can’t access UI Elements from another thread. To overcome this situation WPF introduced a dispatcher. Almost all UI Elements are derived from the DispatcherObject class. This class contains two methods CheckAccess and VerifyAccess. CheckAccess method returns true if the calling thread has access to this object and VerifyAccess throws an exception if the calling thread does not have access to that object. So using this simple functionality all WPF objects are being able to determine that they only used by UI Thread.

Dependency Object

Dependency Object is the base class that supports Dependency Property and Attached Property. The Dependency Properties are used in Data Binding. You can create your own Dependency Property by deriving Dependency Object to you own class. Dependency Object has two Major methods GetValue and SetValue. GetValue method used to get value from Dependency Property and SetValue method used to set value to Dependency Property.

Visual

Each and every element that has visual representation and appears in WPF Window is derived from Visual class. Visual class provides some basic Drawing functionality to encapsulate drawing instructions also some drawing related information like clipping, opacity etc. It also has some basic methods to add and remove visuals. Visual class also provides link between managed libraries and milcore.dll that renders display.

UI Element

UI Element added support for Layout, Focus, Input, Event, command bindings, etc. These are the core and essential features of WPF. At UI element level basic layout is introduced – Measure and Arrange passes. The measure allows determining that how much size it would take and Arrange allows a parent to determine the final size of each child. UI Element also introduces the notation of command binding.

Framework Element

Framework element extends layout features of UI Element and adds support for features like data binding, animation and styles. It also supports key properties like HorizontalAlignment, VerticalAlignment, and Margin etc.

Control

Control is the base class for almost all controls available in WPF such as Button, StatusBar, Combobox, Label, etc. At this level many control level properties introduced like background, foreground, and Font related properties like FontSize, FontStyle, font-weight, etc.

For more info, you can watch below video.

WPF Architecture

In this blog, we will learn WPF Architecture. WPF is used for developing desktop application and was introduced by Microsoft in .NET Framework 3.5 as a replacement of Windows forms.

It has mainly 2 parts – WPF module and OS core Module. WPF module is sub divided in 2 parts – Managed Module ( Core WPF elements) and un-managed module which acts as a bridge between WPF managed module and OS Core element.

Managed Module:

PresentationFramework.dll: This section contains high-level features like application windows, panels, styles controls, layouts, content and so on that helps us to build our application. 

PresentationCore.dll: This is a low-level API exposed by WPF providing features for 2D, 3D, geometry and so on.

WindowsBase.dll: It holds the more basic elements that are capable to be reused outside the WPF environment like Dispatcher objects and Dependency objects.

Un Managed Layer

This section is unmanaged code because it acts as a bridge between WPF managed and the DirectX / User32 unmanaged API.

milCore.dll: It is called the Media Integration Layer (MIL) and resides in milCore.dll. The purpose of the milCore is to interface directly with DirectX and provide basic support for 2D and 3D surface.

WindowsCodecs.dll: WindowsCodecs support in WPF applications like image processing, image displaying and scaling and so on.

Core operating System Layer (Kernel)

This layer has OS core components like User32, GDI, Device Drivers, Graphic cards and so on. These components are used by the application to access low-level APIs.

DirectX: DirectX is the low-level API through which WPF renders all graphics. DirectX talks with drivers and renders the content. 

User32: User32 actually manages memory and process separation. It is the primary core API that every application uses. User32 decides which element will be placed where on the screen. 

GDI: GDI stands for Graphic Device Interface. GDI provides an expanded set of graphics primitives and a number of improvements in rendering quality.

CLR: WPF leverages the full .NET Framework and executes on the Common Language Runtime (CLR).

Device Drivers: Device Drivers are used by the applications to access low-level APIs.

To Summarize it, you can watch this video.

In the next post, we will learn about WPF Class Heirarchy.

Custom Exception Handling in Python

Hello folks, In the previous post we have got the basic understanding of Exception handling in python. And, Today’s agenda will be custom exception handling – how we can force raise an exception, define and create custom Exception classes.

Let us imagine you need to write a code to validate your input and the validation criteria is input should be an integer and it should be between 1 to 10. If the validation criteria fail, we have to throw valid exceptions.

My first solution will be something like this.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):
            print('input is valid')
        else:
            print("input is invalid")
    except Exception as ex:
        print(ex)

But in this code we have ignored various scenarios like

  • Input maybe not integers and then mathematical operators will not work and it will throw an exception.
  • we are not actually raising an exception if the validation criteria do not match.

Raise Custom Exception

so let us say how can we force raise any exception. To do it, we use the raise keyword in python. so modify the above code and use the raise keyword in the else block.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):
            print('input is valid')
        else:
            raise Exception("Input is Invalid")
    except Exception as ex:
        print(ex)

Create Custom Exception Class

Now what we want to do is to handle the validation criteria and throw custom exceptions based on validation criteria. so create custom Exception classes.

class VALRANGEERROR(Exception):
    def __init__(self,message):
        self.message=message
        super().__init__(self.message)

Here we have created a class called VALRANGEERROR and setting its message in constructor so that we can provide custom messages while raising this exception. After this modify our method to raise our custom Exception class.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):   
            print('input is valid')
        else:
            raise VALRANGEERROR("Input is not in range")
    except ValueError as ex:
        print(f"Value Error - {ex}")
    except VALRANGEERROR as ex:
        print(f"Custom Exception - {ex}")
    except Exception as ex:
        print(ex)

So, to summarise this, use the raise keyword to force raise an exception. To implement a custom Exception class, Create a class that inherits from class Exception and assigns the message field in the constructor.

Exception handling in Python

Exception or Error

There can be 2 type of error – Syntax Error or Exceptions.

Synax error encounters if you do not follow language syntax guidelines. common scenarios to face such errors are:

  1. you do not follow proper indentation.
if a= 0 print(a) else print('NA')

2. Suppose you have a method which takes 2 arguments and while calling it, you are providing only one argument.

def return_sum(a,b):
    return a+ b

val = return_sum(3)

There are multiple scenarios like this. In short, a syntax error occurs if the python interpreter fails to parse your code. Now let us discuss exception.

Exceptions are any unwanted thing which may interrupt the control flow of program.

Common Exceptions which you may face with python are – Name Error, Type Error, Runtime Error, or when you are working with files. In short, we can call exception as error faced while coding execution.

a = 10
b = a/0
 #Division by 0 Error
print("Var"+ 1) #Type Error 
print(c) #Name Error
with open('filedoesnotexist') as f: #OSError
    f.read()

your code will break as the exception encounters. Here you can see that control flow of the program is stopped because of ZeroDivisionError and that’s why the code below that statement never gets executed.

Exception Handling

To solve these scenarios we need to perform exception handling. If I am asked to give a crisp description of these keywords, I will say something like this.

put your IO method or DB related methods in a try block in which you think exception may occur. If an exception occurs, Handle it in Except block. If there is no exception, Put it in the else block. And if you want to run some methods whether exceptions are encountered or not, put it in finally block like cleaning up activity, closing the DB connections or releasing the resources.

There are 4 Keyword for Exception handling in python.

  • Try: Run this code
  • Except – Run this code if Exception occurs
  • Else – Run this code if Exception does not occur
  • Finally – Run this code always whether an Exception occurs or not.

Let us consider you want to write a program to get the value of a variable from a file and then delete it. If the file does not exist then you reset the value to 0 in the file.

import os
val=None
try:
    with open('filedoesnotexist.txt') as f:
        val = f.read()
except Exception as identifier:
    val=0
    with open('filedoesnotexist.txt','w') as f:
        f.write(str(val))
else:
    os.remove('filedoesnotexist.txt')
    print("Exception did not occured. Good Job")
finally:
    print(val)
    

To avoid the Name Error i have created val variable globally as it is being used in try, except and finally block. There is Input output operation so i have put the logic to read filedoesnotexist.txt in try block. If the file does not exist, we are resting the value of val to 0 and writing it to filedoesnotexist.txt. And if the file exists then we will not get any error so i am deleting that file and finally printing the value of val variable.

I Hope you got the basic idea of Exception handling. In the next post, I will tell you how to raise custom exception, create user defined Exception and how to debug the stack trace.

Hackerrank java Introduction loops II

In this post, we will solve Hackerrank Java Introduction loops II Challenge.

Problem statement :

You are given queries in the form of a, b, and n. For each query, print the series corresponding to the given a, b, and n values as a single line of space-separated integers.

Explanation

Here we have been given 3 things – a, b, n. so now try to learn the series pattern.

you are given q queries means you have to loop through or process the series q times. if you will concentrate on the series structure you will get the series pattern.
 

we are having a geometric progression of 2 multiplied by b and we are adding this with a.

Example:

first term = a + pow(2,0)*b = 5 + 1*3 = 8
second term = a + pow(2,0)*b + pow (2,1)*b = 5 + 1*3 + 2*3 = 14
third term =  a + pow(2,0)*b + pow (2,1)*b + pow (2,2)*b = 5 + 1*3 + 2*3 + 4*3 = 26
similarly
nth term =  a + pow(2,0)*b + pow (2,1)*b + pow (2,2)*b + ——- + pow (2,n-1)*b
 
so what we will do is that.. we will make a loop and iterate it to n-1 times starting from 0.
 
 for (int j = 0; j < n; j++) {
   a += (int) Math.pow(2, j) * b ;
    System.out.print(a + " ");
}

for more clarification watch – 

If you have any confusion please let me know in the comment box. I would be happy to help you. you can subscribe to the channel if you want to learn more about hackerrank java challenges. 

let's do it

Exit mobile version