My Thoughts & Views

Archive for the ‘C#’ Category

Interfaces
–contain only abstract methods
–interface can’t be inherited from a class
–using interfaces we can achieve multiple inheritance
–doesn’t allow accessibility modifiers (Public/Private/Internal)
–can’t contain fields, constructors
–is must implementable & its scope is upto any level of its inheritence chain.

Abstract Class
–contain both abstract methods as well as concrete methods
–can extend another class and implement multiple interfaces
–we can’t achieve multiple inheritance
–allows accessibility modifiers
–can contain fields, constructors
–class Abstract class is must inheritable & its scope is upto derived class

Steps:
1. Add wnvhtmlconvert.dll to Project Reference under Visual Studio


2. Import it into your code behind file “using Winnovative.WnvHtmlConvert;”

3. Add your PdfConverterKey into Web.Config

<add key=”PdfConverterKey” value=”your key here”/>

4. Write Below Code (Click to Expand)

And you are done.
Let me know if you have any questions

Method :

Usage :

I need to write comments for the below code, bcoz of lack of time i am posting only abstract things,if you want to know something, write comment, i will reply.

HTML login control

< input type="text" name="txtUserName" id="txtUserName" class="textBoxes" />

jQuery Rule: Add the below rule into script tag in header & add reference to jquery-1.2.6.js,jquery.validate.js in Head Element

$(document).ready(function() {

$("#frmSelfRegister").validate({
rules: {
txtUserName:
{
required: true,
remote: { type: "post",
url: "Register/IsLoginAvailable" }
},
messages:{

txtUserName: { required: "User Name is Required.",
remote: jQuery.format("{0} is not available.")}
}
});
});

The above validation code executed when the focus changes from txtUserName to some other, it will call IsLoginAvailable method available in the RegisterController, as specified in the url.

Controller Code :

Below code is the one which checks for availability of a username & returns the status to above jQuery Method. The following methods return type is JsonResult because remote method of jQuery accepts the JsonResult object only.

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult IsLoginAvailable(FormCollection collection)
{
JsonResult result = new JsonResult();

try
{
ilogIn.Text = this.GetLoginByUsername(collection.Get("txtUserName").
ToString().Trim());

}
catch (Exception ex)
{
Helper.ErrLogger(ex.Message);
}

if (ilogIn.Text == collection.Get("txtUserName").ToString())
{
result.Data = false;
}
else
{
result.Data = true;

}
return result;
}

Suppose you have two interfaces, lets say Interface-IA, Interface-IB & in both you have declared Name as a property as follows.

public interface IA
{

string Name { get; set; }
String Adress { get; set; }

}

public interface IB
{

string Name { get; set; }

}

Now, you write an interface -IC which derives from above 2 Interfaces as below,

public interface IA
{

int Id { get; set; }

}

When you are try to do the following, you will get an error saying ‘Ambiguity between IA.Name and IB.Name’.

class Test
{

public void GetSomething()
{
IC objIc = new IC();
Textbox1.Text = objIc.Name();
}

}

It can be solved by upcasting as below.

class Test
{

public void GetSomething()
{
IC objIc = new IC();
Textbox1.Text = ((IA)objIc).Name();
}

}

The DateTime class is not very exact and only can measure in milliseconds. When doing performance measuring on an application you most certainly need to be able to measure with smaller time units than that. High-resolution timers are supported in the Win32 API so following code wraps it up in a simple class:

public class PerformanceTimer
{
[DllImport(“Kernel32.dll”)]
public static extern void QueryPerformanceCounter(ref long ticks);

long startTime = 0;
long stopTime = 0;

public void Start()
{
QueryPerformanceCounter(ref startTime);
}

public void Stop()
{
QueryPerformanceCounter(ref stopTime);
}

public long Time
{
get
{
return stopTime – startTime;
}
}
}

I’m sure the code is easy to understand. Here is the sample code to show how to use it.

PerformanceTimer perfoTimer = new PerformanceTimer();
perfTimer.Start();

// Do something

perfTimer.Stop();
System.Diagnostics.Trace.WriteLine(perfoTimer.Time);

Problem : Calculate the sum of a column in a dataset

Solution :
After filling the dataset from your query you can calculate the sum of a numeric column.

Dataset’s DataTable provides a default method called Compute through which you can perform any aggregate function based operation on columns in a DataTable.

Suppose you have

1. Column : Salary
2. DataSet : dsData
3. DataTable Name : Payroll

Then

dsData.Tables(“Payroll”).Compute(“SUM(Salary)”, String.Empty)

Gives the sum of that column.

Compute accepts two arguments : 1. Expression (Any aggregate Expression)
2. Filter (Any Filtering option, here String.Empty means no filter value)

 public static String Reverse(String strParam)
{
if(strParam.Length==1)
{
return strParam;
}
else
{
return Reverse(strParam.Substring(1)) + strParam.Substring(0,1);
}
}

This is second in series of Interview Questions for .NET Application developer position.

C#

* Does C# supports multiple inheritence?
* What is a delegate?
* What are setallite assemblies?
* Differences between Namespace, Class, Assembly?
* What is the difference between managed and unmanaged code?
* What is serialization?
* What’s a bubbled event?
* What is garbage collection? How dot net handles the garbage collection?
* Can we force garbage collector to run ?
* What is concept of Boxing and Unboxing ? Do we have the same problem in c# 2.0? if no how it is resolved? What are generics?
* What happens in memory when you Box and Unbox a value-type?
* What are the ways to deploy an assembly?
* What is the difference between the value type and reference type? Do we have value type in dot net?
* What different types of JIT compliler do we have?
* What’s a multicast delegate?

C# 2.0

* What are the partial classes? Where we can use them?
* Any idea of LINQ project?
* What are generics?

C# Distributed Application

* What different option do we have for creating distributed applications in dot net?
* What is a thread? What is multithreading?
* What is deadlock? How we can elimate the risk?
* This data structure is “Thread Safe” what does that mean?
* What are locks and why we need them? When working with shared data in threading how do you implement synchronization ?
* What are sockets? What is the difference between TCP and UDP sockets?
* Any idea of Windows Communication Foundation?
* What is the difference between a thread and a process? Can a process have multiple threads?
* How we can communicate betweem two processes?
* What is the procedure of communicating between two threads?
* What’s Thread.Join() in threading ?
* What are the different states of a thread?

— It is slowest sorting algorithm in use
— It is considered as Most In efficient Sorting Algorithm.

How it works?

The basic idea is to compare two neighboring objects, and to swap them if they are in the wrong order. This process is repeated until it completly sorts the list. This causes larger values to “bubble” to the end of the list while smaller values “sink” towards the begining of the list.

C# Code :

// integers array to hold values
private int[] a = new int[100];

// number of elements in array
private int x;

// Bubble Sort Algorithm
public void sortArray()
{
int i ;
int j ;
int temp ;

for( i = (x 1); i >= 0; i)
{
for( j = 1; j <= i; j++ )
{
if
( a[j-1] > a[j] )
{
temp = a[j-1] ;
a[j-1] = a[j] ;
a[j] = temp ;
}
}
}
}

In Computing, a fundamental problem related to lists is Sorting (or Ordering) them in Ascending or Descending.

In this series i would like to explore the Sorting Algorithms from C# point of View.

Following is the list of Commnon Sorting Algorithms in use

  1. Bubble Sort
  2. Insertion Sort
  3. Selection Sort
  4. Quick Sort
  5. Shell Sort
  6. Heap Sort
  7. Merge Sort

1 public sealed class SingletonClass
2 {
3
private SingletonClass()
4
{
5 }
6
7 private static SingletonClass instance = new SingletonClass();
8
9 public static SingletonClass Instance
10 {
11 get
12
{
13
if(instance == null)
14
{
15 instance = new SingletonClass();
16 return instance;
17 }
18
else
19
return instance;
20
}
21
}
22
}

I dynamically add controls to my form, and also i need the option to remove them again.So first i did this to remove,(as per my logic)

foreach(Control contrl in this.Controls)
{
if (contrl .GetType() == typeof(TextBox))
{
this.Controls.Remove(contrl );
}
}

But this code removed only alternative textboxes. At first i was unable to find it out,but then after searching on net i found that when you remove a control from the ControlCollection, subsequent controls are moved up to fill that space. And found the solution to my problem. The code that must be used is like below.

foreach (Control contrl in this.Controls)
{
if (contrl.GetType() == typeof(TextBox))
{
ContrlToRemove.Add((TextBox)contrl);
}
}

foreach (TextBox txtbox in ContrlToRemove)
this.Controls.Remove(txtBox);

Other Alternatives:
1. You can do it in a single loop when removing items from any sort of indexed container,it is always best to remove them in reverse order starting at the end.And also when manually removing windows controls from a container,it is best to Dispose them at the same time. Otherwise you may have a memory leak.

If you find other alternatives too keep me informed.

using System;

class test
{

private static void Main()
{

Console.WriteLine(“Is ‘ada’ Palindrome : {0}”,IsPalindrome(“ada”));
Console.ReadLine();
}

public static bool IsPalindrome(String strParam)
{
int iLength,iHalfLength;
iLength = strParam.Length – 1;
iHalfLength = iLength/2;

for(int iIndex=0;iIndex<=iHalfLength;iIndex++)
{
if(strParam.Substring(iIndex,1)!=strParam.Substring(iLength – iIndex,1))
{
return false;
}
}
return true;
}
}

// Get the Operating System From Environment Class
OperatingSystem os = Environment.OSVersion;
// Get the version information
Version vs = os.Version;

MessageBox.Show (vs.Major.ToString());
// vs.Major;
//vs.Minor;
//vs.Revision;
//vs.Build;

using System.Diagnostics;

private void AddLog(string sErrSource, string sErrMessage, EventLogEntryType ErrType)
{
EventLog objLog = new EventLog(“AppLog”);
objLog.Source=sErrSource;
objLog.WriteEntry(sErrMessage,ErrType);
}
This function will create an event log called “AppLog” and adds the source and message into that.
EventLogEntryType enum contains
1. Error
2. FailureAudit
3. Information
4. SuccessAudit
5. Warning


Blog Stats

  • 71,043 hits
August 2020
M T W T F S S
 12
3456789
10111213141516
17181920212223
24252627282930
31  

Top Clicks

  • None