Showing posts with label .Net. Show all posts
Showing posts with label .Net. Show all posts

How to get File and Function Details from Exception object

Its better to use ErrorLog in Exception Handling. In ErrorLog we need to keep track of the File and the Function details where this Exception occurs. So, instead of sending the Hardcoded Values (i.e : Function Name , File Name ) to ErrorLog, we can directly get this details from Exception object (i.e : Exception ex) as follows :

Code :

Use namespace :
using System.Diagnostics;
using System.Reflection;
Function where Error Occurred :

        /// <summary>
        /// Set AssetName for the AssetID
        /// </summary>
        /// <param name="programId"></param>
        /// <param name="languageId"></param>
        /// <param name="assetId"></param>
        /// <param name="assetName"></param>
        public void SetAssetName(Int32 progId, Int32 langId, int astId, string astName)
        {
            AssetClient assetClient = null;
            try
            {
                assetClient = new AssetClient(appBindingAssets);
                //return assetClient.SetAssetName(progmId, langId, astId, astName);
            }
            catch (Exception ex)
            {
                //call ErrorLog using the File Details
                LogError(ex);
            }
            finally
            {
                if (assetClient != null)
                {
                    assetClient.Close();
                }
            }
        }
ErrorLog Function accepts Exception object as Parameter :
        /// <summary>
        /// Logs the exception. 
        /// </summary>
        /// <param name="ex"></param>
        public static void LogError(Exception ex)
        {
            // Get the File Details from Exception
            StackTrace st = new StackTrace(ex);
 
            // Get the object of MethodBase from StackTrace
            MethodBase mb = st.GetFrame(st.FrameCount - 1).GetMethod();
 
            // Get FileName with NameSpace 
            // Ex: IGroup.Modules.SalesZone.Controller.SalesZoneController"
            string source = mb.DeclaringType.FullName;
 
            // Get Function Name "GetPhraseTranslationList"
            string methodName = mb.Name;
 
            //Implement ErrorLog Logics here using the File Details
            //AddLogError(source, ex, methodName);
        }

Reflection

Reflection is one of the features of .Net framework and has greater importance during the development of large applications.

In brief it is a powerful way of collecting and manipulate information present in application's assemblies and its metadata. Metadata contain all the Type information used by the application. The ability to obtain information at run time also makes it even more advantageous.

When reflection is used along with system.type, it allows the developer to get the valuable information about all the types and about the assemblies. We can even create the instances and then invoke various types that are used across the application.

What is Reflection?
  • Reflection is the ability to find out information about objects, the application details (assemblies), its metadata at run-time.
  • This allows application to collect information about itself and also manipulate on itself.
  • It can be used effectively to find all the types in an assembly and/or dynamically invoke methods in an assembly.
  • This includes information about the type, properties, methods and events of an object and to invoke the methods of object Invoke method can be used too.
  • With reflection we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.
  • If Attributes (C#) are used in application, then with help of reflection we can access these attributes.
  • It can be even used to emit Intermediate Language code dynamically so that the generated code can be executed directly.
How to use Reflection in our applications?
  • System.Reflection namespace contains all the Reflection related classes. These classes are used to get information from any of the class under .NET framework.
  • The Type class is the root of all reflection operations. Type is an abstract base class that acts as means to access metadata though the reflection classes.
  • Using Type object, any information related to methods, implementation details and manipulating information can be obtained.
  • The types include the constructors, methods, fields, properties, and events of a class, along with this the module and the assembly in which these information are present can be accessed and manipulated easily.
  • we can use reflection to dynamically create an instance of any type, bind the type to an existing object, or get the type from an existing object.
  • Once this is done appropriate method can be invoked, access the fields and properties.
  • This can be done by specifying the Type of object or by specifying both assembly and Type of the object that needs to be created.
  • By this the new object created acts like any other object and associated methods, fields and properties can be easily accessed.
  • With reflection we can also find out about various methods associated with newly created object and how to use these object.
  • To find out the attributes and methods associated with an object we can use the abstract class MemberInfo, this class is available under the namespace System.Reflection.

Function to Validate Number of Digits Before and After Decimal Point in TextBox

Usage : On KeyPress Event we Can call the function to Validate the Text Box.
ChkDecimalNumbers(txtNo,e,2,3)
Parameter : Textbox , KeyPressEventArgs , Number of Digits before Decimal & Number of Digits After Decimal
Output :22.987
Asc(x.KeyChar) = 8 : It Represent BackSpace

    Code :
    Shared Sub ChkDecimalNumbers(ByVal ctxt As TextBox, ByVal x As System.Windows.Forms.KeyPressEventArgs, ByVal bfrDec As Int16, ByVal aftDec As Int16)
        If (Char.IsControl(x.KeyChar) Or Char.IsDigit(x.KeyChar) = True) Or x.KeyChar = "." Or Asc(x.KeyChar) = 8 Then
            If ctxt.Text.IndexOf(".") <> -1 Then
                If x.KeyChar = "." Then
                    x.Handled = True
                End If
                If ctxt.SelectionStart >= 0 And Asc(x.KeyChar) <> 8 Then
                    If (((Mid(ctxt.Text, ctxt.Text.IndexOf(".") + 1).Length > aftDec And ctxt.SelectionStart > ctxt.Text.IndexOf(".")) Or (Mid(ctxt.Text, 1, ctxt.Text.IndexOf(".") + 1).Length > bfrDec And ctxt.SelectionStart < selectionlength = 0))) Then
                        x.Handled = True
                    End If
                End If
            Else
                If (aftDec = 0 And x.KeyChar = ".") Or (((Mid(ctxt.Text, 1).Length > bfrDec - 1 And x.KeyChar <> "." And Asc(x.KeyChar) <> 8) Or (ctxt.SelectionStart > bfrDec And x.KeyChar.ToString.Equals("."))) And ctxt.SelectionLength = 0) Then
                    x.Handled = True
                End If
            End If
        Else
            x.Handled = True
        End If
    End Sub 

Common Function to Check the TextBox is blank or not

Parameter : Textbox, & TextBox Description
Output : Returns False, Popup the Message like "Name Can Not Be Blank."

Code :
    Shared Function ChkBlank(ByVal CTxt As TextBox, ByVal CTxtNam As String) As Boolean
        If Len(CTxt.Text.Trim()) > 0 Then
            CTxt.Text = UCase(CTxt.Text)
            Return True
        Else
            MessageBox.Show(CTxtNam & " Can Not Be Blank", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            CTxt.Focus()
            Return False
        End If
    End Function

Get Random Passward (String) Using GUID, Passward Length (Maximum) 32 Char

Get Random Passward (String) Using GUID

 GUID - Represents a Globally unique identifier.
 Purpose : Function For Generatind Password Using System.Guid.NewGuid()
 Paramete : Length - Passward Length (Maximum) 32 Char

Code :
    Public Function GetRandomPasswordUsingGUID1(ByVal length As Double) As String
        Dim guidResult As String = System.Guid.NewGuid.ToString
        guidResult = guidResult.Replace("-", String.Empty) 'Use to Remove "-" from Random Passward
        If length <= 0 OrElse length > guidResult.Length Then
            Throw New ArgumentException("Length must be between 1 and " & guidResult.Length)
        End If
        Return guidResult.Substring(0, length)
    End Function 

Get Random Passward (String) Using GUID , Passward Length (Maximum) 36 Char

Get Random Passward (String) Using GUID

 GUID - Represents a Globally unique identifier.
 Purpose : Function For Generatind Password Using System.Guid.NewGuid()
 Paramete : Length - Passward Length (Maximum) 36 Char

 Code :
   Public Function GetRandomPasswordUsingGUID(ByVal length As Double) As String

       Dim guidResult As String = System.Guid.NewGuid.ToString
       If length <= 0 OrElse length > guidResult.Length Then
           Throw New ArgumentException("Length must be between 1 and " & guidResult.Length)
       End If
       Return guidResult.Substring(0, length)
   End Function

Function To Get the Difference between 2 Dates in different Formats

Purpose : Function To Get the Difference between 2 Dates .
In the Form of : Day ,DayOfYear ,Hour,Minute,Month,Quarter Second,Weekday,Week Of Year,Year
Use : DateInterval.Day / DateInterval.DayOfYear ....

Code :
    Public Sub DateDifference()
        Dim DateDiffVal As Long
        DateDiffVal = DateDiff(DateInterval.Year, DateTimePicker1.Value, DateTimePicker2.Value)
        MsgBox("Date Difference Is : " & DateDiffVal, MsgBoxStyle.DefaultButton1, "Information")
    End Sub 

Use Track Bar to Change the Font Size of the label Dynamically

Change the Font Size Dynamically of the Label by drag the Track Bar

Drag and drop one Label(Name - lblDisply) & one Track Bar
Then Write the coding in TrackBar1_Scroll() Event.


Code :
    Public Class frmUseTrackBar

        Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
            lblDisply.Font = New System.Drawing.Font("Microsoft Sans Serif", (9 + CType(TrackBar1.Value, Double)), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            ' 9 + CType(TrackBar1.Value, Double) : 9 - For Intial Font Size. TrackBar1.Value - Increase the Font size using this value
        End Sub

    End Class

Encrypt OR Decrypt a String Using ASCII Character in Dot Net.

Using this we can Encrypt OR Decrypt a String for security Purpose.
Using this we can EnCrypt the password & save in Back end. Then while retrieving again we can Decrypt the password.


Code :
    Public Class frmEnCryptDeCrypt

    #Region "btnEnCryptDeCrypt Click"
        Private Sub btnEnCryptDeCrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnCryptDeCrypt.Click
            txtResult.Text = fnEnCryptDeCrypt(txtInput.Text)
        End Sub
    #End Region

    #Region "EnCrypt or DeCrypt String"
        Public Function fnEnCryptDeCrypt(ByVal Text As String) As String
            Dim strTempChar As String = "", i As Integer
            For i = 1 To Len(Text)
                If Asc(Mid$(Text, i, 1)) < strtempchar = " CType(Asc(Mid$(Text," > 128 Then
                    strTempChar = CType(Asc(Mid$(Text, i, 1)) - 128, String)
                End If
                Mid$(Text, i, 1) = Chr(CType(strTempChar, Integer))
            Next i
            Return Text
        End Function
    #End Region

    End Class

Gadget

This content is not yet available over encrypted connections.