Thursday, July 22, 2010

Load external DLL from Silverlight

public partial class MainPage : UserControl
{
private string xmlPath;

public MainPage()
{
InitializeComponent();

this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("http://localhost:56121/SL/Test/Test1.dll", UriKind.RelativeOrAbsolute));
}

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
AssemblyPart assemblyPart = new AssemblyPart();
Assembly assembly = assemblyPart.Load(e.Result);

UserControl userControl = assembly.CreateInstance("Test1.MainPage") as UserControl;

if (userControl != null)
{
LayoutRoot.Children.Add(userControl);
}
Type type = userControl.GetType();
MethodInfo[] methodInfoArray = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (MethodInfo methodInfo in methodInfoArray)
{
if (methodInfo.Name == "XMLLoad1")
{
methodInfo.Invoke(userControl, new object[] { "http://localhost:56121/SL/Test/Test1.xml" });
break;
}
}
}
}

Tuesday, July 20, 2010

Suffle a List and Find the index of Item

int index = infoList.IndexOf(item);

public class Util
{
public static List RandomPermutation(List list)
{
List retList = new List(list);
//list.CopyTo(retList.ToArray(), 0);

Random random = new Random();
for (int i = 0; i < list.Count; i++)
{
int swapIndex = random.Next(i, list.Count);
if (swapIndex != i)
{
T temp = retList[i];
retList[i] = retList[swapIndex];
retList[swapIndex] = temp;
}
}
return retList;
}
}

Monday, July 19, 2010

How to Retrieve Subdomain from URI

Hi,

Herewith, I have given below the code to retrieve the uri.

Uri uri = new Uri("http://t1.testing.com/Web1.aspx?Id=5");

public static string RetrieveSubDomain(Uri url)
{
string subDomain = "";
if (url.HostNameType == UriHostNameType.Dns && (!(url.HostNameType == UriHostNameType.Unknown)))
{
string host = url.Host;
int length = host.Split('.').Length;
if (length > 2)
{
int lastIndex = host.LastIndexOf(".");
int index = host.LastIndexOf(".", lastIndex - 1);
subDomain = host.Substring(0, index);
}
}

return subDomain.ToLower();
}

Monday, May 17, 2010

Parse XML file in Javascript

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
function verify() {
if (xmlDoc.readyState != 4) {
return false;
}
}
function ParseSliderXML(path) {
xmlDoc.async = "false";
xmlDoc.onreadystatechange = verify;
xmlDoc.load(path);
var ticker = xmlDoc.documentElement;
//alert(ticker);
return ticker.xml;
}

Monday, April 26, 2010

How to get the online user count in a website

1) Add the tag in your web config file under system.web tag.

membership defaultprovider="TestProvider"
providers
add name="TestProvider" type="System.Web.Security.SqlMembershipProvider" connectionstringname="Test"
providers
membership


2) Use sql server for session state

3) int count = Membership.GetNumberOfUsersOnline();

Monday, August 24, 2009

WPF Interview Questions

1) What is WPF?
2) What are the container controls in WPF?
3) Is ADO.NET supported in WPF?
4) Explain dependency properties?
5) What's a style?
6) What's a template?
7) What is Routed Events & Commands?
8) What is Custom Controls in WPF?
9) How can worker threads update the UI?
10) Differences between Silverlight 2 and WPF
11) What is MVVM and MVP?

Tuesday, July 21, 2009

Silverlight and WCF Interview Questions

Silverlight:

1) What is Silverlight?
2) What are the container controls in Silverlight? Give me the brief explanation.
3) How to load the Flash control in Silverlight?
4) What is Silverlight.js file?
5) How to communicate flash into silverlight?
6) Does Silverlight support ADO.NET? and How to load the data to Silverlight from database?
7) How to use the styles in Silverlight? Can we load the external CSS file into Silverlight?
8) What is the difference between Data Form and Data Pager?
9) Video streaming in Silverlight?
10) How to embed the Silverlight xap file in html page?
11) what is xap file?
12) what is xaml?
13) can we use more than one xaml file in same project? explain?
14) what is StoryBoard?
15) How to use charts and Reports in Silverlight?
16) what is 3D animation in Silverlight?


WCF:

1) What is the difference between WCF and ASMX?
2) What is binding in WCF?
3) What binding is supported in Silverlight?
4) WCF security
5) Dead Letter Queues
6) Poison Message
7) Fault Contracts
8) What is it the Reliable session?
9) What is it the Transmission queue and the Target queue? What is the difference?
10) Could the two-way service operations be used with queued binding?
11) What is it a correlation?
12) How can we create a singleton service?
13) How to set the timeout property for the WCF Service client call?
14) What is Transaction?

Wednesday, July 1, 2009

Types of Serialization

serialization is the process of converting an object into a sequence of bits so that it can be persisted on a storage medium (such as a file, or a memory buffer) or transmitted across a network connection link.

Emp emp = new Emp();
emp.Id = 1;
emp.Name = "S.Bala";
MemoryStream ms = new MemoryStream();

//Binary
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(ms, emp);
ms.Position = 0;
Emp empGet = binaryFormatter.Deserialize(ms) as Emp;
ms.Close();

//SOAP
ms = new MemoryStream();
System.Runtime.Serialization.Formatters.Soap.SoapFormatter soapFormatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
soapFormatter.Serialize(ms, emp);
ms.Position = 0;
empGet = new Emp();
empGet = soapFormatter.Deserialize(ms) as Emp;
ms.Close();

//XML
ms = new MemoryStream();
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Emp));
xs.Serialize(ms, emp);
ms.Position = 0;
empGet = new Emp();
empGet = xs.Deserialize(ms) as Emp;
ms.Close();


[Serializable]
public class Emp
{
public int Id;
public string Name;
}

Sunday, May 17, 2009

ASP.NET AND SQL SERVER Interview Questions

SQL SERVER:

1) DDL/DML triggers
2) Joins
3) Sql Profiler
4) DTS Packages
5) Sql server agent.
6) how to find the second maximum record.
7) how to find the 11 maximum record.
SELECT * FROM (
SELECT ROW_NUMBER() OVER(ORDER BY [TimeStamp]) AS RowId,*
FROM [LOG]) AS Collections
WHERE
Collections.RowId > 45
AND
Collections.RowId < 51
8) sql server 2005 vs sql server 2000
9) How to fetch the records of second highest marks in each section of the class.
10) Normalization forms?
11) Primary key, foreign key, candidate key, composite key, unique key explanation?


ASP.NET:

1) Session management
2) Client side session management
3) Validation controls
4) Web.config authentication, authorization
5) Generics
6) Page life Cycle
7) SDLC
8) web controls vs custom controls
9) Application vs Caching
10) Interface vs Abstract
11) Sealed Classes vs Serializable classes
12) Partial classes
13) Master page
14) MultiThreading and Single Thread
15) Events vs Delegates
16) Types of Serialization
17) static vs normal constructor
18) How to create object for the class and it is holding one private constructor only
19) Forms vs windows authentication
20) custom error page
21) mobile application vs normal web application difference
22) Singleton
23) Abstract class objects
23) Interface objects
24) try catch finally
25) Method overloading and overriding

Thursday, April 9, 2009

How to install Silverlight

This is the article describe the prerequisite needed to create Silverlight development environment.

1) Visual Studio 2008 with SP1 service pack.
2) Silverlight3_Tools.exe which installs the Silverlight tool boxes and application files from Here

3) Microsoft Expression Blend.exe which is used to design the xaml page.


4) Silverlight 3 Toolkit March 2009.msi which contains the samples.

Monday, March 16, 2009

No visual studio template information found

No visual studio template information found in VS 2005 or VS 2008

Soln:

Just open VS command prompt and type the following command..

devenv /installvstemplates


ex:

C:\Program Files\Microsoft Visual Studio 8\VC>devenv /installvstemplates

Friday, January 16, 2009

Create Session in asp.net

Cretae Session:

Session["UserID"] = UserId;
Session.Timeout = 30;
FormsAuthenticationTicket formAuthenticate = new FormsAuthenticationTicket(1, UserId.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), true, FormsAuthentication.FormsCookiePath);
HttpCookie cookies = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(formAuthenticate));
cookies.Expires.AddYears(1);
Response.Cookies.Add(cookies);


Get Session:

string guidSession = HttpContext.Current.User.Identity.Name.ToString();

Tuesday, December 30, 2008

Resize Image with Aspect ratio

Response.ContentType = "Image/Jpeg";
System.Drawing.Image img = System.Drawing.Image.FromFile(@"images1.jpg");
float percent = 100;
if (img.Width > img.Height)
{
if (img.Width > 100)
{
float width = (float)img.Width / 100;
percent = percent / width;
}
}
else
{
if (img.Height > 100)
{
float heigth = (float)img.Height / 100;
percent = percent / heigth;
}
}

System.Drawing.Image image = ImageManipulator.ScaleByPercent(img,(int)percent);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
img.Dispose();



public class ImageManipulator
{
public ImageManipulator()
{
//
// TODO: Add constructor logic here
//
}
public static Image ScaleByPercent(Image imgPhoto, int Percent)
{
float nPercent = ((float)Percent / 100);

int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;

int destX = 0;
int destY = 0;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);

grPhoto.Dispose();
return bmPhoto;
}
}

Sunday, December 21, 2008

Basic SQL queries

create table Test (Id int Primary Key identity(1, 1), [Name] varchar(50) not null)
alter table Test alter column [Name] int not null
alter table Test add [Age] int not null
delete from Test
DBCC CHECKIDENT (Test, RESEED, 0)
create trigger TestTrigger on Test
FOR INSERT, UPDATE, DELETE
AS
select getDate()
DISABLE TRIGGER ImageTestTrigger ON ImageTest
ENABLE TRIGGER ImageTestTrigger ON ImageTest

drop table Test
DROP trigger TestTrigger

insert into Test([Name], [age]) values('SBala', 25)
update Test Set age = 24 where [Name] = 'SBala'
delete from Test where [Name] = 'SBala'

Create function GetTest() Returns int
as
begin
declare @count int
set @count = (select count(*) from Test)
return @count
end


select dbo.GetTest() as [Count]


begin tran tt
delete from Test
rollback (or) Commit

select * from emp
select e1.[Name], e2.[Name] as Head from emp e1, emp e2
where e1.Head = e2.Id


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER Procedure [dbo].[Emp_Get](@Name varchar(10), @Created varchar(50),
@PhoneNumber int)
as
begin
declare @query varchar(5000)

set @query = 'select * from EMP where '
if(@Name != 'null')
set @query = @query + ' Name = ' + @Name
if(@Created != 'null')
set @query = @query + ' and Created = ' + @Created
if(@PhoneNumber != 0)
set @query = @query + ' and PhoneNumber = ' + cast(@PhoneNumber as varchar(50))
exec(@query)
end



alter Procedure Emp_Get(@Name varchar(10), @Created varchar(50),
@PhoneNumber int)
as
begin
declare @query varchar(5000)

set @query = 'select * from EMP where '
if(@Name != 'null')
set @query = @query + ' Name = ' + @Name
if(@Created != 'null' and @Name != 'null')
set @query = @query + ' and Created = ' + @Created
if(@Created != 'null' and @Name = 'null')
set @query = @query + ' Created = ' + @Created
if(@PhoneNumber != 0)
begin
if(@Created != 'null' or @Name != 'null')
set @query = @query + ' and PhoneNumber = ' + cast(@PhoneNumber as varchar(50))
else
set @query = @query + ' PhoneNumber = ' + cast(@PhoneNumber as varchar(50))
end
exec(@query)
end

Monday, December 15, 2008

Select records from a Table between Row Numbers

select * from (
select ROW_NUMBER() over (Order by [column_name]) as RowId, *
from [table_name]) as Collections
where Collections.RowId > 10 and Collections.RowId < 20

Tuesday, December 9, 2008

Difference between Session and Cookies

Difference between Session and Cookies
1. The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not.
2. But Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.
3. The Key difference would be cookies are stored in your hard disk whereas sessions aren’t stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
4. A session as is a server-side object which stores State. A cookie is a small piece of information a browser sends to a server with every request.
5. Session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browse
6. Session and cookies differ in type and amount of information they are capable of storing.
Unable to use SQL Server because ASP.NET version 2.0 Session State is not installed on the SQL server. Please install ASP.NET Session State SQL Server version 2.0 or above.

This issue normally occurs when we use sql server for storing session. To overcome this issue, we have to do the following steps.

1) sessionState mode="SQLServer" allowCustomSqlDatabase="true" sqlConnectionString="data source=server_name;database=aspnetdb;user id=user;password=pass" cookieless="false" timeout="120" this tag should be in the web.config file.
2) Run the following command from the dot net installed directory.
aspnet_regsql.exe -ssadd -sstype c -d databasename -E

ex: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regsql.exe -ssadd -sstype c -d DATABASENAME -E

Thursday, December 4, 2008

Getting the List of Installed softwares from the local system

Here is the sample code to get the list of softwares installed in the system.


const uint HKEY_LOCAL_MACHINE = unchecked((uint)0x80000002);
ManagementClass wmiRegistry = new ManagementClass("root/default",
"StdRegProv", null);
//Enumerate subkeys
string keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
object[] methodArgs = new object[] { HKEY_LOCAL_MACHINE, keyPath, null };
uint returnValue = (uint)wmiRegistry.InvokeMethod("EnumKey", methodArgs);
MessageBox.Show("Executing EnumKey() returns: " + returnValue);
if (null != methodArgs[2])
{
string[] subKeys = methodArgs[2] as String[];
if (subKeys == null) return;
ManagementBaseObject inParam =
wmiRegistry.GetMethodParameters("GetStringValue");
inParam["hDefKey"] = HKEY_LOCAL_MACHINE;
string keyName = "";

foreach (string subKey in subKeys)
{
//Display application name
keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" +
subKey;
keyName = "DisplayName";
inParam["sSubKeyName"] = keyPath;
inParam["sValueName"] = keyName;
ManagementBaseObject outParam =
wmiRegistry.InvokeMethod("GetStringValue", inParam, null);

if ((uint)outParam["ReturnValue"] == 0)
{
listBox1.Items.Add(outParam["sValue"]);
}
}
}

Wednesday, December 3, 2008

Get Logical disk drives using C# code

This is the sample code to get the disk drives, cd, removable disk etc...

private void PopulateDriveList()
{
const int Removable = 2;
const int LocalDisk = 3;
const int Network = 4;
const int CD = 5;
//const int RAMDrive = 6;

//Get Drive list

ManagementObjectCollection queryCollection = getDrives();
foreach ( ManagementObject mo in queryCollection)
{
switch (int.Parse( mo["DriveType"].ToString()))
{
case Removable: //removable drives

break;
case LocalDisk: //Local drives

break;
case CD: //CD rom drives

break;
case Network: //Network drives

break;
default: //defalut to folder

break;
}
}

}
protected ManagementObjectCollection getDrives()
{
//get drive collection
ManagementObjectSearcher query = new
ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
ManagementObjectCollection queryCollection = query.Get();
return queryCollection;
}

Create Database and tables using C# code

This is the sample code to create database and its tables, Views and SP.

string conStr = "Data Source=server_name; Initial Catalog=Master; User ID=dummy; Password=dummy;";
FileInfo fileInfo = new FileInfo(@"C:\1.sql");
string script = fileInfo.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("select [name] from sys.databases", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
List databaseList = new List();
while (dr.Read())
{
databaseList.Add(dr[0].ToString());
}
conn.Close();
if (databaseList.Contains("TestDB1"))
{
MessageBox.Show("Database already exists.");
}
else
{
cmd = new SqlCommand("Create Database TestDB1", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conStr = "Data Source=server_name; Initial Catalog=TestDB1; User ID=dummy; Password=dummy;";
conn = new SqlConnection(conStr);
cmd = new SqlCommand(script, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Database created successfully.");
}