Wednesday, December 21, 2011

N-Largest salary without using top keyword or max key word in Sql server


N-Largest salary without using top keyword  or max key word in Sql server

This the commom questions often ask in the interview how to find out the 2nd,3rd…….. or nth laragest salary or data from the table.
Its not a comlecated question  and you are ok with top key word but he want to  know something different and he asks you that show me the same out put without using Max or top key word…………….
This time you are blank
Ok lets starts the practice to find out the Nth largest salary with out using top or Max key word.
select * from
(
select row_number() over(order by a.AmountReceived desc) as row,a.AmountReceived from
(
select distinct  AmountReceived from LoungeAccessHistory
)a
)b where b.row=3


The same way you can find out the complete details of employee from the table who have Nth largest salary like this
Or
Find out the compete detail of employee who have 3rd largest salary into the compay

select * from LoungeAccessHistory
where
AmountReceived=(select b.AmountReceived from
(
select row_number() over(order by a.AmountReceived desc) as row,a.AmountReceived from
(
select distinct  AmountReceived from LoungeAccessHistory
)a
)b where b.row=3
)


Nth Largest salary using Correlated Query
Declare @n int
Set @n=3
Select  AmountReceived
  from LoungeAccessHistory E1 where (Select Count(Distinct(E2.AmountReceived))
 From
LoungeAccessHistory E2 Where E2.AmountReceived >= E1.AmountReceived)= @n
 order by E1.AmountReceived desc

Nth Largest salary using DENSE_RANK () function of Sql Server
Declare @n int
Set @n=3
select * from
(
select DENSE_RANK () over(order by AmountReceived desc) as row,* from LoungeAccessHistory
)a where a.row=@n

Thursday, September 8, 2011

Micro Soft API For Language Converter(Englsih to Chinise)

microsoft provides API service for the language converter. using this you can convert one language to other languae. Here I am putting the code for converting the English words to chinese words. If you want to convert any other language to any other languae you can also achive this. Because microsoft bing translator provides a lot of languges support and enhanceing the translating power day by day.






References :- http://www.microsoft.com/web/post/using-the-free-bing-translation-apis


To get your Bing App ID, visit http://www.bing.com/developers/appids.aspx, and sign in with your Windows Live ID
Before using the above code include the following name spaces:




using System.Net;
public string micorsoftApi(string wordToBeTranslate)
{
//Creating the object of proxy
WebProxy p = new WebProxy();
//crating nexwork crediential
NetworkCredential nc = new NetworkCredential("NetworkOrSystemUserId", "NetWorkOrSystemPassword", "YourNetWorkDomainName");
string proxyURL=”put the URL of your Network proxy”
p = new WebProxy(proxyURL, true, null, nc);
//setting applicaiton Id Bing translator appId change the application //id according to applicaiton you get the the application id for the //perticuler URL after registed that site on Bing BD
string appId = "xyz";//Get API ID by registed on bing and put here
string tobetranslated = wordToBeTranslate.Trim();
//setting from language parameter en for english
string fromLang =”en”;
//settting to language parameter zh-CHT for chainis traditional and //zh-CHS for chinise simplified
string toLang =”zh-CHS”;
string translatedText = string.Empty;
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?appId="+ appId + "&text=" + tobetranslated + "&from=" + fromLang + "&to=" + toLang;
//creating object and of webrequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
//setting proxy and network credentials to web request
request.Proxy = p;
request.Credentials = nc;
//geting the response from bing appi
WebResponse response = request.GetResponse();
//reading the the data form response as stream
Stream strm = response.GetResponseStream();
StreamReader reader = new System.IO.StreamReader(strm);
translatedText = reader.ReadToEnd();
//wriint the converted text into chinise
Response.Write("The translated text is: '" + translatedText + "'.");
// lbl.Text = "The translated text is: '" + translatedText + "'.";
response.Close();
return translatedText;




}


Other Refrences:-
http://sdk.microsofttranslator.com/
http://www.microsofttranslator.com/mix2010/
http://www.microsofttranslator.com/
http://www.microsofttranslator.com/dev/


Hope this code will help all of you.


Jai Durga Ji Ki
Praveen Kumar Singh Bisen

UDF for splite string in Sql Server

/****** Object: UserDefinedFunction [dbo].[fnStringSplitter] Script Date: 09/08/2011 12:42:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from LoungeAccessHistory where CardNumber like '55%'


/*******************************************************************************************************/
-- Author: Praveen Kumar Sing Bisen
-- Date: 29/8/2011 /*******************************************************************************************************/
Create Function [dbo].[fnStringSplitter]
(
@IDs Varchar(max), --A big string which may have delimeter in it or not
@Delimiter Varchar(1) -- Delimeter to use for splitting up the given string
)
/*********************** RETURN *********************/
--Returns the table with specific values in a temporary table. Useful especially if you have any IDs in the
--given string and want to get them as a table row values.
-- Example:
--@IDs = 1,2,3,4,5,6,7,8,9,10
--@Delimeter = ','
--Returns @Tbl_IDS, which is having 10 rows with above IDS in each row by splitting up with given delimeter [in this example ',']
/****************************************************/
Returns @Tbl_IDs Table (ID Varchar(500)) As
Begin
--Remove the leading delimiter if any
while (substring(@IDs,1,1) =@Delimiter)
set @IDs = substring(@IDs, 2,len(@IDs)-1)

-- Append comma
Set @IDs = @IDs + @Delimiter

-- Indexes to keep the position of searching
Declare @Pos1 Int
Declare @pos2 Int
Declare @RowNum Int

-- Start from first character
Set @Pos1=1
Set @Pos2=1
While @Pos1 Begin
Set @Pos1 = CharIndex(@Delimiter,@IDs,@Pos1)
Insert @Tbl_IDs Values (Substring(@IDs,@Pos2,@Pos1-@Pos2))
-- Go to next non comma character
Set @Pos2=@Pos1+1
-- Search from the next charcater
Set @Pos1 = @Pos1+1
End
Return
End

Procedure to send the Mail using SqlServer


We can use this procedure to send the mail from backend

create Procedure sp_SendMail   
 @mailBody varchar(8000),   
 @mailSubject varchar(2000),   
 @mailTo varchar(max),   
 @mailCCList varchar(max)   
As   
 --Set the profile name   
 Declare @emailProfileName as nvarchar(50)   
 select @emailProfileName=[value] from SystemConfig where [Name]='SenderAccountProfileName'   
   
 --configure mail profile if not already there   
 if Not Exists(SELECT profile_id, * FROM msdb.dbo.sysmail_profile WHERE name =@emailProfileName)   
  exec ConfigureMail   
   
   
 --Send Email   
 if(Len(RTrim(@mailTo)))>0   
 begin   
  EXEC msdb.dbo.sp_send_dbmail    
   @profile_name = @emailProfileName,   
   @recipients = @mailTo,   
    @copy_recipients = @mailCCList, 
   @subject = @mailSubject,   
   @body = @mailbody,   
   @body_format = 'HTML' ;   
 end   
    

Sunday, May 8, 2011

Dynamic Link Libraries Inside-Out - Advantages and Disadvantages of Using DLLs


Advantages/Disadvantages of Using DLLs
• Low Memory Usage -- The code and data that we compile in a DLL is shared among the applications that use the DLL. Moreover depending on the way you load a DLL in your application, it’ll be loaded only when needed. Either way it uses less memory.
The code inside the DLL is resident in the read-only sections and loaded in memory pages marked as read-only. It allows the system to map the DLL into the address space of the processes that uses it. Yes, the DLL is loaded just once, and if a process requests using it, the operating system just maps the DLL to calling application’s address space.
• Reduced Swapping -- Imagine two processes using the same DLL and one of them finishes its job and exits. But the DLL won’t unload now because the DLL manages its lifetime by keeping a reference count of the processes that use it. It unloads itself as soon as the reference count drops to zero, a stage where any process is not using it.

Now assume that a new process begins and requests the system to load the same DLL that is now being used by an already running application. So what happens next? Does the system load the DLL again? No! Certainly not. The currently loaded DLL has all its code and data in memory and the system just maps this to the address space of the new process and it works just fine. So it saved a lot of work on the operating system’s part, which would have involved reading the DLL code and data from the disk file.

• Use as an Off the Shelf Component -- Once you’ve built a DLL after proper design, you may use it in any application you find suitable. Think of it as a component that you’re very sure about in terms of functionality. You just drop this in one of your projects, and it should work fine.
Imagine a DLL implementation that provides all the calculations which are required while developing a graphics rendering application. This DLL can now be used in any project that requires these calculations.
• Interoperable between Languages -- The DLL written in one language might be used in applications written in a different language. It’s common for developers to write optimized routines in assembler and package them as a DLL and later call them from a C++ or Visual Basic application.
On a developer's part, it’s unfortunate that most of the languages provide support for using the DLLs but only a few let one create them. But still it’s a benefit that one may use a DLL written by someone else. This doesn’t only allows one to focus on the business logic and be away from the hassle of writing some complex routines, but also freedom from the debugging and testing of this module. Imagine performing I/O in a Visual Basic application using a DLL that uses the inportb and outportb instructions from the native CRT library. DLLs make writing such interoperable code a breeze.
• Can Provide After Market Support -- What if you find after shipping a product that it needed some alterations. It’s a troublesome job to rebuild and redistribute the whole application to all the buyers. But it can be avoided if you design your application in well-defined modules packaged into DLLs. You could just make the DLL available as an upgrade to the whole package and the product should work fine. Read on the disadvantages which might fake this point, but I’ll say that it’s just the way you write your code.
• The DLL Hell -- It’s the biggest trouble that DLLs sometimes cause. You might have encountered situations where a program fails to load, displaying some error such as “The ordinal abc could not be located in the dynamic-link library xyz.dll.”  Or you install a new application and some other programs starts to malfunction or even fails to load. These are just the symptoms of DLL hell on your machine. The most common source being a irresponsibly made install program that doesn't check versions before copying DLLs into the system directory. This may also happen if a newer DLL has replaced an older one and has major changes in the functionality. DLLs should be backward-compatible, but it's the proper design of the application that ensures backward compatibility and in most cases is hard to achieve.


Friday, May 6, 2011

How load a user control at run time

1) Add the content place holder on the web page.
2)put the following code at required place.



 Control MyUserControl = (Control)this.Page.LoadControl("UserControls/LoadUCatRunTime.ascx");
             lit.Controls.Add(MyUserControl);

How to Save a file into database and display on the user browser


Here we will learn how to save a file into sqlserver database using asp.net in encripted form.



First Create a Table into Database having name EncriptFile with the following fields:-

Create Table EncriptFile(Id int primary key identity(1,1), FileName varchar(50), ContentType varchar(50), FileData VarBinary(MAX))


Step 2:- Create a aspx page having a fileUploader control and Button Controll

btnUpload refers the Upload button
Upload refers the FileUpload control

Setp: 3:- Put the Following code on the Click Event of Upload button Controll this code will save the file into database table in encrypted formate. Please Optimize this code according to your Requirement.

protected void btnUpload_Click(object sender, EventArgs e)
{
string FilePath = Upload.PostedFile.FileName;
string FileName = Path.GetFileName(FilePath);
string ext = Path.GetExtension(FilePath);
string contenttype = string.Empty;
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != string.Empty)
{
Stream fs = Upload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string strQuery = "insert into EncriptFile(FName,ContentType,Data) values(@Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("@Name", FileName);
cmd.Parameters.AddWithValue("@ContentType", contenttype);
cmd.Parameters.AddWithValue("@Data", bytes);
InsertUpdateData(cmd);
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}

private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["praveen"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}

Setp 4:- using the following code we will display the file on the page by fatching from the database

private void getImage()
{
SqlDataReader red;
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["praveen"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand("select * from EncriptFile", con);
cmd.CommandType = CommandType.Text;
con.Open();
red = cmd.ExecuteReader();
if (red.Read())
{
Byte[] bytes =(Byte[]) red["Data"];
// MemoryStream Ms = new MemoryStream();
// Ms.Write()
//Response.ContentType = red["ContentType"].ToString();
//Response.BinaryWrite(bytes);
Response.Clear() ;
Response.ClearHeaders() ;
Response.AddHeader("Content-Disposition", "attachment;filename=praveen.pdf");
Response.AddHeader("Content-Length", bytes.Length.ToString()) ;
Response.ContentType = red["ContentType"].ToString() ;
Response.BinaryWrite(bytes) ;
Response.End();
}
con.Close();
}




Tuesday, February 1, 2011

Linq To Sql Interview Questions and other interview Questions



Difference between LINQ and Stored Procedures?

There are couple of advantage of LINQ over stored procedures.
1.Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries

2.Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.

3.Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!


Pros and Cons of LINQ (Language-Integrated Query)

 
  • What are the pros and cons of LINQ (Language-Integrated Query)?
  • What are the best and worst cases in which to use LINQ?
  • How have you benefitted or not benefitted from using LINQ?
  • Which data sources benefit the least and the most from LINQ?


Disadvantages of LINQ over Stored Procedures

  1. PreCompiled: Stored Procedures are precompiled, and LINQ queries need to compile before execution. So stored procedures are fast in performance.

Advantages of LINQ over Stored Procedures

Disadvantages of LINQ over stored procedures:
  • LINQ needs to process the complete query, which might have a performance impact in case of complex queries against stored procedures which only need serialize sproc-name and argument data over the network.
  • LINQ is generic, whereas stored procedures etc can take full advantage of the complete database features.
  • If there has been a change, the assembly needs to be recompiled and redeployed whereas stored procedures are much simpler to update.
  • It’s much easier to restrict access to tables in database using stored procedures and ACL’s than through LINQ. 


 Are LINQ to SQL entities Business Entities or Data Transfer Objects?

 Are LINQ to SQL entities Business Entities or Data Transfer Objects?  How do I build a business layer on top of LINQ to SQL?


 How do I get default values from the database when inserting new entit

 How do I get default values from the database when inserting new entities?

What is Language Integrated Query (LINQ)?
LINQ is a set of extensions to .NET Framework that encapsulate language integrated query, set and other transformation operations. It extends VB, C# with their language syntax for queries. It also provides class libraries which allow a developer to take advantages of these features.

Difference between LINQ and Stored Procedures.
Difference between LINQ and Stored Procedures:
  • Stored procedures normally are faster as they have a predictable execution plan. Therefore, if a stored procedure is being executed for the second time, the database gets the cached execution plan to execute the stored procedure.
  • LINQ supports type safety against stored procedures.
  • LINQ supports abstraction which allows framework to add additional improvements like multi threading. It’s much simpler and easier to add this support through LINQ instead of stored procedures.
  • LINQ allows for debugging using .NET debugger, which is not possible in case of stored procedures.
  • LINQ supports multiple databases against stored procedures which need to be re-written for different databases.
  • Deploying LINQ based solution is much simpler than a set of stored procedures 



Pros and cons of LINQ (Language-Integrated Query) 


Pros of LINQ:
  • Supports type safety
  • Supports abstraction and hence allows developers to extend features such as multi threading.
  • Easier to deploy
  • Simpler and easier to learn
  • Allows for debugging through .NET debugger.
  • Support for multiple databases
Cons of LINQ:
  • LINQ needs to process the complete query, which might have a performance impact in case of complex queries
  • LINQ is generic, whereas stored procedures etc can take full advantage of database features.
  • If there has been a change, the assembly needs to be recompiled and redeployed. 

Can I use LINQ with databases other than SQL Server? Explain how
LINQ supports Objects, XML, SQL, Datasets and entities. One can use LINQ with other databases through LINQ to Objects or LINQ to Datasets, where the objects and datasets then take care of database specific operations and LINQ only needs to deal with those objects, not the database operations directly. 


What is assembly manifest? What is the information it provides? - June 03, 2009 at 11:00 AM by Shuchi Gauri

What is assembly manifest? What is the information it provides?

Assembly Manifest is a file that contains data that describes how the elements present inside an assembly are connected to each other. The assembly manifest contains assembly metadata to define the scope of the assembly and resolve references to resources and classes.
Information provided by Assembly Manifest:
a. Assembly Name
b. Version Number
c. Culture
d. Strong name
e. List of files inside the assembly
f. Reference information

What are Satellite assemblies and how to generate Satellite assemblies?

To support the feature of multiple languages, we need to create different modules that are customized on the basis of localization. These assemblies created on the basis of different modules are knows as satellite assemblies.
Steps to generate satellite assemblies:
a. Set the paths for resgen and al.exe:
b. Create a .resources file.
c. Create the satellite assembly.
d. The assembly should have the naming convention for .NET to be able to search for it.
e. Specify the settings for culture.
f. Put the satellite assembly in the appropriate folder.
g. Once the satellite assembly is created, physically copy it to the appropriate directory.
h. Repeat the process for each language in which you are creating an assembly.

What is Satellite Assembly?

Satellite Assemblies are language-specific assemblies and are used for language-specific resources for an application. Each assembly of this kind has a separate language specific ID and is installed in a language-specific subdirectory for each language.




Define AL.EXE and RESGEN.EXE

Al.exe: It embeds the resources into a satellite assembly. It takes the resources in .resources binary format.
resgen.exe:The input for Al.exe is generally plain text or XML-based resource files i.e. in .resx format. resgen.exe is used to convert such resources to the .resource in binary format which makes then compatible with al.exe.


Explain the concepts and capabilities of Assembly in .NET


An assembly is a collection of files (dll’s, exe’s), group of resources that help in creating a logical unit of functionality. It forms the basic building block for deployment, reusability and security issues.
  • It provides a CLR environment.
  • It helps in maintaining security as it grants grant or denial of permissions.
  • When an application starts only assemblies the application initially calls must be present.
  • Assemblies can be either static or dynamic.
  • Assemblies help in resolving versioning issues.
What is Globalization and Localization in ASP.NET?

Define Resource Files and Satellite Assemblie

Resource Files:A resource file contains non-executable data that are used by the application and deployed along with it. Bitmaps, Icons etc are the examples of resource files. In ASP.NET, resource files are used to make application to support multiple cultures. You can create resource files each of them correspond to specific locale or culture of the application. You can use resgen utility to compile resource file into an assembly. You can create a satellite assembly from a compiled resource file using the AL utility provided with Microsoft .NET SDK.
Advantages of resource files are as follows.It supports Globalization features in ASP.NET.
You can have culture based information separate from the content and logic of the application.
You can change resource content without effecting application's code. 
Satellite Assemblies Satellite Assemblies are the special kinds of assemblies that exist as DLL and contain culture-specific resources in a binary format. They store compiled localized application resources. They can be created using the AL utility and can be deployed even after deployment of the application.
Satellite Assemblies encapsulate resources into binary format and thus make resources lighter and consume lesser space on the disk.

Note: Resource-only assemblies can contain any resource, such as images and text. Satellite assemblies contain only culture-specific resources.


Difference between candidate key and primary key
Candidate Key– A Candidate Key can be any column or a combination of columns that can qualify as unique key in database. There can be multiple Candidate Keys in one table. Each Candidate Key can qualify as Primary Key.
Primary Key– A Primary Key is a column or a combination of columns that uniquely identify a record. Only one Candidate Key can be Primary Key.
One needs to be very careful in selecting the Primary Key as an incorrect selection can adversely impact the database architect and future normalization. For a Candidate Key to qualify as a Primary Key, it should be Non-NULL and unique in any domain. I have observed quite often that Primary Keys are seldom changed. I would like to have your feedback on not changing a Primary Key.