Tag Archives: .Net

Brief Difference between Static Class & Non-Static Class in C# .net


List out all the table names & it’s info of selected Database using SQL Server


–Select YourDatabase

USE AdventureWorks

Go

–Query to list out all the Tables in the selected DB

SELECT * FROM sys.Tables

 

In Above result, all rows are not ordered on any basis. You can given more specific query to sort out / ordered by any column. For example, now we considered the column “Name” to display the result in ordered.

 

–Same Result which is Alphabetically ordered by the Column “Name”

SELECT * FROM sys.Tables ORDER BY [name]

 

You can observe in the above result. All rows are ordered by the column “Name”. See it’s very right??? Like this simple & twisting, we can see a lot unless you get a situation.

 

Happy Coding….

 

How to Remove Last n Letter / Character from the given String using SQL Server


Here ‘m going to remove 3 letter / character from the given string. You can consider any number of letter to remove.

When i came to need it, i searched a lot. Yes Ofcourse i got lot of answers in many logic way. But among all the answers finally i got this solution as very easy to understand & easy to fix. its just a small piece of code to put in b/w query.

Let us see…

— Remove last 3 letter from the String

DECLARE @String VARCHAR(50)

SET @String = ‘TESTSTRING123AB’

— Chop off the end character

SET @String = LEFT(@String, LEN(@String) – 3) — can specify any number

SELECT @String AS Result

Please let me know, if you have any questions….

Happy Coding…

How to Access a Textbox (or any control) Value from UserControl(.ascx) to Page(.aspx) using ASP.NET C#


HTML Source in UserControl (WebUserControl1.ascx)

<%@ Control Language=”C#” AutoEventWireup=”true” CodeFile=”WebUserControl.ascx.cs” Inherits=”WebUserControl” %>

<table align=”center”>

<tr>

<td colspan=”2″><b>How to Access a Value from UserControl(.ascx) to Page(.aspx)</b></td>

</tr>

<tr>

<td>Enter Your Name: </td>

<td><asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox></td>

</tr>

</table>

Design View in UserControl (WebUserControl1.ascx)

Code Page of UserControl (WebUserControl1.ascx.cs)

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

public partial class WebUserControl : System.Web.UI.UserControl

{

protected void Page_Load(object sender, EventArgs e)

{

}

//public property to get the value from the textbox1

public string YourName

{

get { return this.TextBox1.Text.Trim(); }

}

//publc property to set the passed value to the textbox1

public string MakeTextBoxEmpty

{

set { this.TextBox1.Text = value; }

}

}

HTML Source in WebPage (Default.aspx)

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<%@ Register src=”WebUserControl.ascx” tagname=”WebUserControl” tagprefix=”uc1″ %>

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

<title>Untitled Page</title>

</head>

<body>

<form id=”form1″ runat=”server”>

<div>

<uc1:WebUserControl ID=”WebUserControl1″ runat=”server” />

<br />

<table align=”center” width=”300px”>

<tr>

<td align=”center”><asp:Button ID=”Button1″ runat=”server” Text=”Get Value”

onclick=”Button1_Click” /></td>

</tr>

<tr>

<td><asp:Label ID=”Label1″ runat=”server” Text=””></asp:Label></td>

</tr>

</table>

</div>

</form>

</body>

</html>

HTML Source in WebPage (Default.aspx.cs)

Code Page of UserControl (WebUserControl1.ascx.cs)

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

Label1.Text = “YourName is: ” + WebUserControl1.YourName;

WebUserControl1.MakeTextBoxEmpty = “”;

}

}

Happy Coding…. 🙂

How to Change Date Format from MM/DD/YYYY to DD/MM/YYYY using Asp.Net C#


Usually we see lots of date format in our daily work routines like 22/04/1988, 04/22/1988, Wednesday  April 22, 1988,   & so many formats….

In some scenario, almost developers face the little overhead over Date format conversion. So, now ‘m going to figure out, how to convert it in many ways. You can opt it which is suitable:

Design View

DateFormatChange - DesignView

 

Inline / HTML Source View

DateFormatChange - SourceView

In Coding Page, We have to handle the Event for Button Click. Here, there is lot of way to achieve this. But i have done in 3 ways. I will show you 3 methods one by one in below. Write the code in Button “btnChangeFormat” Click event (Double click on button).

1st Method:

ButtonClickEvent - Method1In this Method, i have used System.Globalization; because ‘m going to convert the datetime variable into culture specific based on region/country.

——————————————————————————————————————-

2nd Method:

ButtonClickEvent - Method2In this Method, i have used simple string.Format method and specifying the format of given datetime variable using String.

——————————————————————————————————————-

3rd Method:

ButtonClickEvent - Method3

In this Method, i have used arrays. its very simple to implementation. 1st i have assigned the date month year by splitting the symbol ‘/’. Later i have retrieved the array element based on array index, that’s it.

 

Happy Coding….

 

 

 

How to Find or List out the Dates occured in given Passage using C# Asp.Net


This is How i have designed on the page.

Inline Source Code Window

Source View of the Designed Page in HTML.

there is so many ways to achieve the result. Now ‘m going to show you one way of them.

Button Click Event:

protected void Button1_Click(object sender, EventArgs e)
{
//assign textbox content to string array varible
//by splitting based on spaces
string[ ] passageWords = TextBox1.Text.Trim().Split(‘ ‘);

//datetime variable for out parameter of Try.Parse()
DateTime parsedDate;

//looping of string array variable
for (int i = 0; i < passageWords.Length; i++)
{
//try to parse the array element, if its true
//then its datetime. Then add this item to Listbox.
if (DateTime.TryParse(passageWords[i], out parsedDate))
{
ListBox1.Items.Add(parsedDate.ToShortDateString());
}
}
}

 

Run this Program:

Run the Program

Happy Coding…

 

How to Find out Vowels Occurances & its Count using C#


Design ViewThis is How i have designed on the page.

Source ViewSource View of the Designed Page in HTML.

You can achieve this in many ways, but i have done in one simple way –

Now, ‘m going to write code for “Check Vowel” Button on Click Event

protected void btnCheckVowels_Click(object sender, EventArgs e)
{
//variable to count the occurances
int count = 0;

//variable to hold the vowels on each loop, we need to add up the things on existing one
//so better to take StringBuilder
System.Text.StringBuilder sb = new System.Text.StringBuilder();

//variable holds the user input by converting it into lower case
string userInput = txtUserText.Text.Trim().ToLower();

//checks whether variable has content or empty
if (!string.IsNullOrEmpty(userInput))
{
//looping on each letter of user input content
for (int i = 0; i < userInput.Length; i++)
{
//variable to hold a letter on each loop
char alpha = userInput[i];

//checking the condition on alpha variable whether it contains, then do the following things.
if (alpha == ‘a’ || alpha == ‘e’ || alpha == ‘i’ || alpha == ‘o’ || alpha == ‘u’)
{
count++;
sb.Append(alpha);
}
}
}

//finally listing the count & which of those vowels on label
lblResult.Text = “No. of Vowels occured: ” + count + “<br />Vowels are: ” + sb;
}

Run this Program:

Result

Happy Coding.

C# (Sharp) Interview Q’s & A’s – Part 5


41. How to implement multiple inheritence in C# ?

Multiple inheritence in C# is achieved by using Interfaces.

42. Why multiple Inheritance is not possible in C#?

Multiple Inheritance is possible in C++, but it’s not possible in Java, and C#.

what we are read above those are all we know, but as per my knowledge, in C++ to resolve multiple inheritance we are using “this pointer”. But in C# there is no pointer concept. In such way, the architectures using the interface concept. To resolving the ambiguity “this pointer” concept used in c++.

Ofcourse it not absolutely correct, but its my idea only. If you are agree with my view then follow it, else leave it.

43. Platform specific code is obtained when ?

MSIL code is the intermediate code which is platform independent.

When MSIL is compiled actual platform dependent code is generated.

44. Method Overloading and Overriding are the same?

Method overloading means having two methods with the same name but different signatures in the same scope. These two methods may exist in the same class or one in base class and another in derived class.

Method overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the

base class and another in the derived class. These cannot exist in the same class

45. How do you inherit from a class in C#?

let’s you have 2classes

Class A is the base class

Class B is the derived class

Class B:A is the syntax to inherit a base class

46. What is JIT?

just in time

47.  Can we inherit the java class in C# class, how?

Java Programming language is not supported with .Net Framework hence you cannot inherit javaclass in C# class. Also Java has JavaByte code after compiling similar to MSIL which is similar but cannot inherit due to framework support.

48. If I want to override a method 1 of class A and in class b then how do you declare ?

declare method1 as virtual in classA and then create classB as derived class of ClassA and override method1 in classB.

class ClassA{

public virtual add();

}

class ClassB:ClassA{

public overrride add(){

console.WriteLine(“Im in derived”);

}

}

49. How do you implement Inheritance in dot net ?

By using “:” we can implement inheritance.

50.  How do you implement Inheritance in dot net ?

In c++ we include the :: operator.

In c# we include the ” : ”

here example

class class1

{

—-

—-

—-

}

class class2 : class1

{

—–

—–

—–

}

when we use the multiple class for implementation, comman(,)  is used to seperate for the class

C# (Sharp) Interview Q’s & A’s – Part 4


31. Sealed class can be inherited ?

sealed classes cannot be inherited as the sealed classes provides full functionality only the classes that have no full functionality can be inherited

32. Public policy applies to?

Public policies are applied on Shared Assemblies.

33. How do you inherit from a class in C#?

Placing Colon(:)

Let’s example

class x

{

//code

}

class y:x(here drive class placing colon)

{

//code

}

34. How’s method overriding different from overloading?

overriding keyword change behavior in derive class with same signature,

Overloading means same name but passing different datatype or different number arguments within the same class

35. Does C# support multiple inheritance?

No, Instead of this, we can inheritance the multiple interface,

but C++ support multiple inheritance

36. Can u create the instance for abstract classes?

No we cannot instanciate abstract class we hav to extend it first

ex- abstract class A

{}

class B : A

{}

37. Can we use Friend Classes or functions in C# the way we use it in C++ ?

No we cannot use friend keyword but instead c# provide “internal” keyword for friend

38. Is it mandatory to implement all the methods which are there in abstract class if we inherit that abstract class..?

No only function marked as abstract shoud be implemented.the following code runs fine abstract public class baseclass { public abstract void method1(); public void method2(){Console.WriteLine(“Base Method 2”);} } public class derivedclass:baseclass { public override void method1(){Console.WriteLine(“Derived Method 1”);} //public override void method2(){Console.WriteLine(“Derived Method 1”);;} }

39. A class type in C# is a value type ?

No

40. Can static methods be overridable?

No

C# (Sharp) Interview Q’s & A’s – Part 3


21. The following namespace is used for globalization ?

The answer is A. The System.Globalization namespace contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency, and numbers, and the sort order for strings. These classes are useful for writing globalized (internationalized) applications. System.Localization and System.Locale currently do not exist in C#. If you don’t believe me look it up on msdn. Or better yet, create a new application in VS and try to add System.Localization or System.Locale; you will find that they do not exist within the Sytem namespace.

22. What is an abstract class?

The abstract modifier can be used with classes, methods, properties, indexers, and events.

Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.

Abstract classes have the following features:

An abstract class cannot be instantiated.

An abstract class may contain abstract methods and accessors.

It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.

A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.

Abstract methods have the following features:

An abstract method is implicitly a virtual method.

Abstract method declarations are only permitted in abstract classes.

Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:

public abstract void MyMethod();

23. Where we can use DLL made in C#.Net ?

Supporting .Net, bcoz DLL made in C#.Net semicompiled version. It’s not a com object. It is used only in .Net Framework. As it is to be compiled at runtime to byte code.

24. Is Structs and classes support inheritance?

structs can inherit interfaces

25. What Datatypes does the RangeValidator Control support?

String, Integer, Double, Date, Currency

26. How do i read the information from web.config file?

string ConStrFromWeb=System.Configuration.ConfigurationSettings.AppSettings[“ConStringKey”];

// Here ConStringKey is the key name of connection string in web.config

27. To start a Thread, Which method u need to call?

Start()

Thread thr=new Thread(new ThreadStart(fn1));

thr.Start();

28. How we hand sql exceptions? What is the class that handles SqlServer exceptions?

SqlExceptionclass is created whenever the .NET Framework Data Provider for SQL Server encounters an error generated from the server. (Client side errors are thrown as standard common language runtime exceptions.) SqlException always contains at least one instance of SqlError.

29. What is the difference between Shadow and Override?

Shadowing :- This is a VB.Net Concept by which you can provide a new implementation for the base class member without overriding the member. You can shadow a base class member in the derived class by using the keyword “Shadows”. The method signature,access level and return type of the shadowed member can be completely different than the base class member.

Hiding : – This is a C# Concept by which you can provide a new implementation for the base class member without overriding the member. You can hide a base class member in the derived class by using the keyword “new”. The method signature,access level and return type of the hidden member has to be same as the base class member.Comparing the three :-

1) The access level , signature and the return type can only be changed when you are shadowing with VB.NET. Hiding and overriding demands the these parameters as same.

2) The difference lies when you call the derived class object with a base class variable.In class of overriding although you assign a derived class object to base class variable it will call the derived class function. In case of shadowing or hiding the base class function will be called.

30. WHAT IS THE ADVANTAGE OF SERIALIZATION?

Serialization is the process of converting object into byte stream which is useful to transport object(i.e remoting),persisting object(i.e files,database).