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

Friday, March 2, 2012

How to use relative paths for an Assembly in the C# projects in order to avoid the conflicts with the references?

Let us consider the following hierarchy of the project



Let us say the working project name is WorkingProject . Follow the following steps in order to use relative paths for the assemblies

1. Add the references to the project (LocalFunctions.dll and LocalClasses.dll) by browsing. To Add reference to a project, right click on the reference folder and click on add reference.

2. Open the physical location of the WorkingProject

3. Edit the .csproj file in notepad++ or notepad.

4. Look for the HintPath tag for each and every reference and check the required relative paths under this tag value.

E.g. in this case it should be like this


a)      ..\..\ LocalSolution \ LocalFunctions \bin\Debug\LocalFunctions.dll
b)      ..\..\ LocalSolution \ LocalClasses\ bin\Debug\ LocalClasses.dll



Note: By default these relative paths will be populated based on the added references w.r.t. current working directly of the project.

If you need any windows assembly use path like

C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll



Thursday, February 18, 2010

How to find no of unique characters in a string using in build functions in c#?

static int GetUniqueCharCountWithInBuiltFunc(string inputString)
{
if (string.IsNullOrEmpty(inputString))
{
throw new NullReferenceException();
}
char[] inputArray = inputString.Replace(" ", "").ToCharArray();
return inputArray.Distinct().Count();
}

How to count unique characters in a string using c#?

static int GetCharacterCount(string inputString)
{
Dictionary charactersDictinary = new Dictionary();
if (string.IsNullOrEmpty(inputString))
{
throw new NullReferenceException();
}
for (int i = 0; i < inputString.Length; i++)
{
if (charactersDictinary.ContainsKey(inputString[i]))
{
i++;
}
else
{
charactersDictinary.Add(inputString[i], i);
}

}
return charactersDictinary.Count;
}

How to count the number of words in given string using c#?

static int GetWordCount(string inputString, bool checkCaseSensitivity)
{
Dictionary charactersDictinary = new Dictionary();
if (string.IsNullOrEmpty(inputString))
{
throw new InvalidOperationException();
}
if (!checkCaseSensitivity)
{
inputString = inputString.ToLower();
}
string[] inputStringArray = inputString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < inputStringArray.Length; i++)
{
if (charactersDictinary.ContainsKey(inputStringArray[i]))
{
i++;
}
else
{
charactersDictinary.Add(inputStringArray[i], i);
}

}
return charactersDictinary.Count;
}

How to find anagrams from a given list of strings using c#?

public static Dictionary> GetAnagramEquivalents()
{

// "cat", "tac", "army", "pam", "act", "map", "mary", "self"
// "act": "act", "cat", "tac"
// "army": "army", "mary"
// "map": "map", "pam"
// "self": "self"


List InputListStrings;

string[] inputStrings = new string[] {"cat", "tac", "army", "pam", "act", "map", "mary", "self","act", "act", "cat", "tac","army", "army", "mary","map","map", "pam","self","self"};
InputListStrings = inputStrings.ToList();
Dictionary> dictionaryReturnList = new Dictionary>();
for (int x = 0; x < InputListStrings.Count; ++x) { char[] InputCharArray = InputListStrings[x].ToCharArray(); Array.Sort(InputCharArray); string InputString = new string(InputCharArray); //check if the dic contains the key then add value to its corresponding list if (dictionaryReturnList.ContainsKey(InputString)) { dictionaryReturnList[InputString].Add(InputListStrings[x]); } else { dictionaryReturnList.Add(InputString, new List());
dictionaryReturnList[InputString].Add(InputListStrings[x]);
}
}
return dictionaryReturnList;
}

How to check whether one string is anagram of other in c#?

static bool CheckAnagramOfString(string inputString1, string inputString2)
{
char[] charArr1 = inputString1.ToCharArray();
char[] charArr2 = inputString2.ToCharArray();
//sort both of them in same order
Array.Sort(charArr1);
Array.Sort(charArr2);
inputString1 = new string(charArr1);
inputString2 = new string(charArr2);

if (inputString1.Equals(inputString2))
{
return true;
}
else
{
return false;
}

}

How to sort a comma separated array elements from a string using c# with Bubble sort?

static void BubbleSort(string inputString)
{
string[] inputStingArray = inputString.Split(' ');
int[] inputIntArr = inputStingArray.Select(x => int.Parse(x)).ToArray();
if (inputIntArr == null || inputIntArr.Length <= 0) { throw new ArgumentException("Inavlid array input"); } int temp; for (int i = inputIntArr.Length - 1; i >= 0; i--)
{
for (int j = 0; j < i; j++) { if (inputIntArr[j] > inputIntArr[j + 1])
{
temp = inputIntArr[j];
inputIntArr[j] = inputIntArr[j + 1];
inputIntArr[j + 1] = temp;
}
}
}

Console.WriteLine("Each individual Item in Array after sorting is");
foreach (int item in inputIntArr)
{
Console.WriteLine(item);
}
Console.ReadKey();
}

Write a c# code to find the factorial of a function?

static int GetFactorial(string inputValue)
{
int number;
bool IsNumber = true;
IsNumber = Int32.TryParse(inputValue, out number);
if (IsNumber)
{
int result = 1;
int counter = number;
do
{
result = result * counter;
counter--;
} while (counter >= 1);
return result;
//with factorial
//if (number <= 1)
//{
// return 1;
//}
//else
//{
// result = number * GetFactorial((number - 1).ToString());
// return result;
//}
}
else
{
throw new Exception("Input value is not a valid number");
}
}

How to find no of occurences of a string in a file using c#?

static int countWordOccurrencesInFile(string filePath, string searchText)
{
// FileStream fstream = File.Open(filePath,FileMode.Open);
using (StreamReader reader = new StreamReader(filePath))
{
string strContents = reader.ReadToEnd();

//Dictionary uniqueWords = new Dictionary();
int occurrences = 0;
int foundPos = -1;
int startIndex = 0;
do
{
foundPos = strContents.IndexOf(searchText, startIndex);
if (foundPos > -1)
{
startIndex = foundPos + 1;
occurrences++;
}
} while (foundPos > -1);

return occurrences;
}
}

How to find duplicate words in a file using c#?

static List countDuplicateWordsInFile(string filePath)
{
// FileStream fstream = File.Open(filePath,FileMode.Open);
using (StreamReader reader = new StreamReader(filePath))
{
string strContents = reader.ReadToEnd();
List duplicateWords = new List();
Dictionary uniqueWords = new Dictionary();
string[] strArray = strContents.Split(new string[] { " ", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < strArray.Length; i++)
{
if (uniqueWords.ContainsKey(strArray[i]))
{
//add duplicate words
duplicateWords.Add(strArray[i]);
}
else
{
//unique words
uniqueWords.Add(strArray[i], i);
}
}

return duplicateWords;
}
}

How to reverse the string in c# using with and without in build functions?

static string RevereseStringWithoutInbuildFunc(string inputString)
{
if (string.IsNullOrEmpty(inputString))
{
throw new NullReferenceException();
}
StringBuilder strBuilder = new StringBuilder();
for (int i = inputString.Length - 1; i >= 0; i--)
{
strBuilder.Append(inputString[i]);
}
return strBuilder.ToString();
}

static string RevereseStringWithInbuildFunc(string inputString)
{
if (string.IsNullOrEmpty(inputString))
{
throw new NullReferenceException();
}
char[] inputArray = inputString.ToCharArray();

Array.Reverse(inputArray);
return new string(inputArray);
}

Tuesday, August 18, 2009

Practical interview asp.net interview questions?

1.The XML file below has a list of employees. Your job is to bind the employee IDs and Names to a dropdownlist. ID must be dropdownlist value field and name must be the dropdownlist Text field. Also, only the active employees must be binded to the dropdownlist and the names should be in the ascending order. When I select a name from the dropdownlist, the name and ID of the selected employee must be printed on the webform.
Employees.xml


David
101
true


Tom
102
true


Rick
103
false


Mark
104
true



Code sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Employees.xml"));

DataView DV = DS.Tables["Employee"].DefaultView;
DV.RowFilter = "IsActive='true'";
DV.Sort = "Name asc";

DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}
---------------------------------------------------------------------------------
2.Write a custom function in c-sharp. The custom function parameters should be an instance of a dropdownlist, an xml file and a string?

The sample code for custom function is shown below. For this example to work drop the XML file in the root folder of the web application.

protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}

public void PopulateDropdownlist(System.Web.UI.WebControls.DropDownList DropDownListObjectToBePopulated,string XMLFilePath, string InitialString)
{
try
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath(XMLFilePath));
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
}
catch(Exception Ex)
{
}
}
--------------------------------------------
3. How to read and write cookies in asp.net?


1. The following example shows how to write a "USER" cookie to a client's computer. The "USER" cookie, stores
FirstName
LastName
LastVisit

2. Create the user interface to enter FirstName and LastName.




3. WriteCookieButton_Click event handler in the code behind file, has the code required to write the cookie to the client computer as shown below.
protected void WriteCookieButton_Click(object sender, EventArgs e)
{
// Create an instance of HttpCookie class
HttpCookie UserCookie = new HttpCookie("USER");
// Populate FirstName, LastName and LastVisit fields
UserCookie["FirstName"] = FirstNameTextBox.Text;
UserCookie["LastName"] = LastNameTextBox.Text;
UserCookie["LastVisit"] = DateTime.Now.ToString();
// Set the cookie expiration date
UserCookie.Expires = DateTime.Now.AddDays(3);
// Write the cookie to the client computer
Response.Cookies.Add(UserCookie);
}

4. ReadCookieButton_Click even handler in the code behind file has the code to read the cookie from the client computer as shown below.
protected void ReadCookieButton_Click(object sender, EventArgs e)
{
// Check if the "USER" cookie exists on the client computer
if (Request.Cookies["USER"] != null)
{
//Retrieve the "USER" cookie into a cookie object
HttpCookie UserCookie = Request.Cookies["USER"];
//Write FirstName,LastName and LastVisit values
Response.Write("First Name = " + UserCookie["FirstName"] + "
");
Response.Write("Last Name = " + UserCookie["LastName"] + "
");
Response.Write("Last Visit = " + UserCookie["LastVisit"] + "
");
}
}

5. Finally test. Run the application and enter first name and Last name and click, the write cookie button. This should write the cookie to the client's computer. Now click the read cookie button, which will read the FirstName, LastName and LastVisit information from the cookie and writes on to the webform.

C# Interview Questions on constructors

What is a constructor in C#?
Constructor is a class method that is executed when an object of a class is created. Constructor has the same name as the class, and usually used to initialize the data members of the new object.

In C#, What will happen if you do not explicitly provide a constructor for a class?
If you do not provide a constructor explicitly for your class, C# will create one by default that instantiates the object and sets all the member variables to their default values.

Structs are not reference types. Can structs have constructors?

Yes, even though Structs are not reference types, structs can have constructors.

We cannot create instances of static classes. Can we have constructors for static classes?
Yes, static classes can also have constructors.

Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below.

using System;
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}

Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in csharp can be overloaded.

Can a child class call the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}

class ChildClass : BaseClass
{
public ChildClass(string str): base(str)
{
}

public static void Main()
{
ChildClass CC = new ChildClass("Calling base class constructor from child class");
}
}
}

If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

Will the following code compile?
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

No, the above code will not compile. This is because, if a base class does not offer a default constructor, the derived class must make an explicit call to a base class constructor by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
//Call the base class contructor from child class
public ChildClass() : base("A call to base class constructor")
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

Can a class have static constructor?
Yes, a class can have static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. An example is shown below.

using System;
namespace TestConsole
{
class Program
{
static int I;
static Program()
{
I = 100;
Console.WriteLine("Static Constructor called");
}
public Program()
{
Console.WriteLine("Instance Constructor called");
}
public static void Main()
{
Program P = new Program();
}
}
}

Can you mark static constructor with access modifiers?
No, we cannot use access modifiers on static constructor.

Can you have parameters for static constructors?
No, static constructors cannot have parameters.

What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Give 2 scenarios where static constructors can be used?

1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Does C# provide copy constructor?
No, C# does not provide copy constructor.

What is an array?
An array is a data structure
that contains several variables of the same type.

What are the 3 different types of arrays?
1. Single-Dimensional
2. Multidimensional
3. Jagged

Are arrays value types or reference types?
Arrays are reference types.

Can you use foreach iteration on arrays in C#?
Yes,Since array type implements IEnumerable, you can use foreach iteration on all arrays in C#.

What is Jagged Array?
A jagged array is an array of arrays.

What is the difference between DataSet.Copy() and DataSet.Clone()?
DataSet.Clone() copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.

Is there a way to clear all the rows from all the tables in a DataSet at once?
Yes, use the DataSet.Clear() method to clear all the rows from all the tables in a DataSet at once.

Can you enforce constarints and relations on tables inside a DataSet?
Yes, the DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects.



What are absoluteExpiration and slidingExpiration parmeters of the Insert and Add methods?
absoluteExpiration

A DateTime object that identifies when the data should be removed from the cache. If you’re using sliding expiration, specify Cache.NoAbsoluteExpiration for this parameter.
slidingExpiration
A TimeSpan object that identifies how long the data should remain in the cache after the data was last accessed. If you’re using absolute expiration, specify Cache.NoSlidingExpiration for this parameter.

Which is the only "event” provided by Cache object?
CacheItemRemoved "event” is the only "event” provided by Cache object.

Thursday, August 13, 2009

How to log the Error/ Exceptions details into the event viewer using c#?

Any kind of exception or error can be logged into the event viewer using few lines of code by writing into Global.asax.cs file of your application.
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
/// Get reference to the source of the exception chain and log the exception into Event Log
void Application_Error(object sender, EventArgs e)
{
//Get reference to the source of the exception chain
Exception ex = Server.GetLastError().GetBaseException();

//Log the details of the exception and page state to the
//Windows 2000 Event Log
EventLog.WriteEntry("My Application",
"MESSAGE: " + ex.Message +
"\nSOURCE: " + ex.Source +
"\nFORM: " + Request.Form.ToString() +
"\nQUERYSTRING: " + Request.QueryString.ToString() +
"\nTARGETSITE: " + ex.TargetSite +
"\nSTACKTRACE: " + ex.StackTrace,
EventLogEntryType.Error);
}

How to remove white spaces between tags and lines of html render by asp.net page ?

When asp.net page loaded in to browser there are lots of white spaces between tags and in tags that will increase your html kb. For example if your page around 300 kb then it will take 3 second to load on 100 kbps internet connection and in dial up connection it will still take time. So if you want to load your site fast on dial up internet connection then you need to decrease html kb as much you can and removing white spaces from the html will be good idea for that.
Following is the code for the page on which you want to remove white spaces from the html. It will decrease your html kb by 30 percentage.

using System.Text;
using System.Text.RegularExpressions;

private static readonly Regex REGEX_BETWEEN_TAGS = new Regex(@">\s+<", RegexOptions.Compiled);

private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"\n\s+", RegexOptions.Compiled);


///
/// Initializes the object and calls on the child
/// controls of the to render.
///

/// The that receives the page content.
protected override void Render(HtmlTextWriter writer)
{
using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
{
this.Page.Title = CommonFunctions.HtmlEncode(this.Page.Title);
base.Render(htmlwriter);
string html = htmlwriter.InnerWriter.ToString();

html = REGEX_BETWEEN_TAGS.Replace(html, "> <");
html = REGEX_LINE_BREAKS.Replace(html, string.Empty);

writer.Write(html.Trim());
}

}

How to move the files from one folder to another folder using C#?

Files can be moved from source to destination using System.IO namespace in c#.
This code will move the files from source directory having 1 sub level of directory or not.
string destination = string.Empty;
string source = string.Empty;
destination = Server.MapPath("Destination");
source = Server.MapPath("Source");

//follwing code can used to move the directory files from one folder to
//another
DirectoryInfo dir = new DirectoryInfo(source);
if (dir.Exists)
{
DirectoryInfo[] subDirs = dir.GetDirectories();
if (subDirs.Length > 0)
{
foreach (DirectoryInfo d in subDirs)
{
FileInfo[] files = d.GetFiles();
foreach (FileInfo f in files)
{
f.MoveTo(destination);
}
}
}
else
{
FileInfo[] files = dir.GetFiles();
if (files.Length > 0)
{
foreach (FileInfo f in files)
{
//f.CopyTo(destination);

f.MoveTo(Path.Combine(destination, f.Name));
}
}
else
{
Response.Write("file does not exists");
}
}
}
else
{
Response.Write("Source Directory Does not exists");
}