Wednesday, October 20, 2010

Get the records during the last month or last week

Question:
I want to query the records during the last month or last week. How can I do this easily?
Answer:
For datetime and smalldatetime, 0 stands for the default value ‘1900-01-01 00:00:00.000’. So you can use the combination of DATEDIFF and DATEADD functions to get rows within a certain period of time.

The last month
SELECT * FROM Orders
WHERE OrderDate >= DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE())-1,0)
AND OrderDate < DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()),0)

The last week
SELECT * FROM Orders
WHERE OrderDate >= DATEADD(WEEK,DATEDIFF(WEEK,0,GETDATE())-1,0)
AND OrderDate < DATEADD(WEEK,DATEDIFF(WEEK,0,GETDATE()),0)

The year before last
SELECT * FROM Orders
WHERE OrderDate >= DATEADD(YEAR,DATEDIFF(YEAR,0,GETDATE())-2,0)
AND OrderDate < DATEADD(YEAR,DATEDIFF(YEAR,0,GETDATE())-1,0)

Here you can replace GETDATE() with any other datetime values.

Get the total working days between two dates(Excluding the Sundays and Saturdays)

Question:
I would like to get the total working days between two dates.
Answer:
You can first calculate the total days and non-working days with DATEDIFF function. Then use subtraction to get working days.

The SQL clause is shown below.

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2009/12/01'
SET @EndDate = '2009/12/31'

SELECT ((DATEDIFF(dd, @StartDate, @EndDate) + 1)
-(DATEDIFF(wk, @StartDate, @EndDate) * 2)
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END))

Friday, October 8, 2010

Crystal report Interview questions and answers

1. What is Crystal Report?

Ans: Crystal report is a report generation tool. Generally have interface with VB6. Crystal report basically generates dynamic data. You can format the data in whichever way you feel like.

2. Can we use Crystal report as a stand-alone application?

Ans: Generally we use Crystal Reports with VB6. However we can make crystal report stand-alone application also. But for that limitation is for viewing the report user should have crystal reports installed on his/her PC.

3. How do we connect to the database?

Ans: There are two ways of creating the report: -

Use crystal report built in query.
Use the tool ‘ Crystal SQL Designer’ provided by crystal report.
When you create report using crystal report built in query then it asks for the data source name that you have created. When you run the report, then for the first time it will ask for the user id and password. After that it will store the same.

When you create ‘.qry’ using ‘Crystal SQL’ Designer then at that time it will ask for the user id and password. When you run the report for the first time instead of asking for the user id and password it will ask for the ‘.qry’ file location. You can change the query location also. For that open the report, select ‘Set Location’ option in Database menu item, and set the location.

4. How do we format field?

Ans: For formatting any field just right click on it and you will get many options like ‘Format Field.’ ‘Browse field data’ etc. Click on ‘Format Field.’ You can align data, suppress, make it multiline, change the font size, style, and type, make it hyperlink etc.

If it is an amount field then you can display currency symbol also. Right click on the field select ‘Format Field’.

5. Can we give parameters to the report?

Ans: We can very well give parameters to the report. For creating parameters select ‘Parameter Field’ in Insert menu item. ‘Create Parameter Field’ dialog box will popped up, it will ask for the name of parameter, prompting text and datatype. Now when you run the report it will prompt for these parameters.

6.Can we create our own formulas in reports?

Ans: We can create our own formulas in reports. Select ‘Formula Field’ in Insert menu item. Write the formula in ‘Formula Editor’. Here you will get ‘Field Tree’, ‘Function Tree’, and ‘Operator Tree’, which will display the report fields, functions that are supported by crystal reports (like CDATE () etc.), operators (arithmetic, strings etc.) respectively.

7. Can we create report using more than one database?

Ans: We can create report using more than one database like Oracle, Access. Create data source name for both the databases. Select tables from them and create the report.

Only restriction is if you use two databases then you cannot see the SQL generated by crystal reports.

8. Can we export data of reports into other format like in world doc etc?

Ans: Generated data can be exported to word doc, or in rich text format. Just click on ‘Export’ icon in the menu. Export dialog box will be popped up. It will ask for the ‘Format’ like comma-separated value (csv) etc and the ‘Destination’ like disk, application etc. After that it will ask for the file name and save the data.

Only restriction is formatting of data will be lost, but crystal report will try to maintain as much formatting as it can.

9. Can we use our own SQL for creating a report?

Ans: We can also make our own query using ‘Crystal SQL Designer’ tool provided by SQL. Here you can insert your SQL statement as such. It will save this file as ‘.qry’ . And when you create a report instead of using ‘Database’ button use ‘Crystal SQL Statement’ button.

10. Can we edit SQL made by Crystal reports?

Ans: We cannot edit the SQL made by crystal reports. However we can view the SQL. For that select ‘Show SQL Query’ in Database menu item. Limitation is if you are using only one database. If you use two databases then you can’t even view the SQL prepared by crystal report.

11. Are there any limitations in crystal reports?

Ans: There are certain limitations in crystal reports. They are: -

If database is having field whose length is more than 255 characters, then you cannot make formula using that field.
While exporting data formatting is lost.
When you browse data just by right clicking on the field then it displays that is there in the database not the data selected by the query.
12. Can we suppress printing in crystal reports if 0 records are fetched?

Ans: Yes, we can suppress printing if no records are fetched. Select ‘Report Options’ in File menu item. ‘Report Options’ dialog box will pop up. In that there is one option ‘ Suppress printing if no records’ Check this option. If no records are found then nothing will be printed on the report.

13. What are the sections that we have in Crystal reports?

Ans: Report has got standard sections like ‘Page Header’, ‘Page Footer’, ‘Report Header’, ‘Report Footer’, and ‘Details’.

However you can add other sections also. Select ‘Sections’ in the Insert menu item. You can insert group sections also.

If you don’t want to show any section just right click on that section and suppress that.

14. Can we add any database field once we have chosen ‘Close’ button?

Ans: Yes, we can add any database field afterwards also. Select ‘Database Field’ in Insert menu item.

If you are using crystal report built in query then it will display the tables that you have selected. And you can select whichever field you want to display on the report.

But if you are using ‘.qry’ file then it will display Query and you can select only those field, which are there in the query.

15. Does Crystal Report support all the functions that we have in Oracle?

Ans: No, Crystal report does not support all the functions. Like Decode function is there in SQL but not there is crystal report. You need to convert that in crystal report format (in if and else etc.).

However if you use ‘.qry’ files then it take the SQL as such. There is no need of changing any syntax.

16. Can we use stored procedure for creating the report?

Ans: Yes, we can use stored procedure.

17. Is there any feature like summing total in crystal report?

Ans: Crystal reports provide features like grand total, sub-total, running total etc. You can select any of these features in Insert menu item.

You can sum up records on the basis of each record or on change of group using ‘Running Total ‘ option in Insert menu item.

18. I am using two tables one is of access database and other is of oracle database, I am getting an error saying that ‘SQL odbc error’ what should I do?

Ans: If you are getting such an error then click the icon for ‘Report Expert’. It will give a warning saying that formatting will be lost. Ignore this you will get ‘Standard Report Expert’ dialog box. Reverse the links of access database table and it will work.

Crystal Report interview questions

Crystal Report writers:

1) What versions have you used and can you describe differences between the versions? - speaks to familiarity and experience with the tool. Also tells me whether the person is a programmer that's dabbled with CR in .net, but may not know the actual tool, which is different, or vice versa - depending on my needs. In my experience, most (but not all) .net CR writers don't really know Crystal Reports and don't understand the most basic functionality of the tool. Of course, most (but not all) die-hard experienced CR writers don't know anything about .net, it depends what you're looking for - the skills tend to be very different even though the tools share the same name of 'crystal'

2) What is 'Set Location' and when would you use it? - speaks to knowledge of very basic functionality

3) Explain the pros and cons of basing a report off tables, Views and Stored Procedures - speaks to knowledge of performance and optimization techniques, as well as understanding of SQL concepts. If an incumbant has only ever report from stored procedures (which he/she may or may not have written), then the interviewee probably doesn't understand basic Crystal Reports Functionality and/or performance and optimization. Likewise, if the interviewee has only every built reports from tables, then he/she probably doesn't understand performance and optimization and my not understand SQL.

4) Describe subreports - when would you use them and when would you avoid them - speaks to knowledge of performance and optimization techniques, data access techniques and functionality

5) What is 'Show SQL Query' and what is it good for? speaks to knowledge of performance and optimization techniques, as well as understanding of SQL concepts

6) What is a 'SQL Expression' field and what are the pros and cons of using one? Nobody knows - seriously - speaks to experience and advanced knowledge (in many cases), as well as understanding of SQL

7) What is a 'SQL Command Object' and what are the pros and cons of using one - speaks to experience and SQL understanding

8) Have you ever built a parameterized report? If so, describe the function of parameters and ways that they can be used to enhance a report's performance or look? How can they be used to optimize report maintenance and reduce redundancy? Speaks to knowledge and experience in true production environments.

9) If a user were to ask you to build a report for them, what types of questions would you ask the user in order to ascertain the true requirements? Speaks to experience and analytic skills

10) What would you do if a user wanted a report that could be exported to excel in spreadsheet format, but the user wanted it to look graphically presentable in Crystal Reports and why? Speaks to experience and creativity

11) Describe the most difficult or complicated report you've ever created. What made it either difficult, complicated or both? Speaks to overall knowledge, experience, creativity, etc...

etc....

I'm a tough interview and these are samples of the types of questions I ask, but not all the questions. I ask questions that allow the interviewees to explain themselves in their own manner so that I can see if they understand both the question and the concept, whether or not they explain it perfectly. I also have years of experience and I can filter out the bs very quickly... I don't believe in yes/no, mutliple choice technical interview questions because I don't believe they are reliable

Regex for email

private bool CheckValidEmail(Entity.BrokerEntity broker)
{
string email = broker.EmailId.Trim();
string emailExpression = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|" + @"0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*([-][a-z|0-9]+)*\.([a-z]" + @"[a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";
//broker.Messages = new List();
Regex regExpEmail = new Regex(emailExpression, RegexOptions.IgnoreCase);

if(string.IsNullOrEmpty(broker.EmailId))
{
broker.Messages.Add("Email id is mandatory");
}
else if(!regExpEmail.IsMatch(email))
{
broker.Messages.Add(string.Format(Helper.InvalidID,"Email id"));
}

return !regExpEmail.IsMatch(email);
}

Regex for Phone Number

System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^([0-9]*)$");
Eg:
if (!(r.Match(broker.PhoneNumber).Success))
broker.Messages.Add("Phone number is invalid");

Web.config settings








defaultCategory="Error" logWarningsWhenNoCategoriesMatch="true">

footer="----------------------------------------" formatter="Text Formatter"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="ErrorLog TraceListener" />
log="Application" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Formatted EventLog TraceListener" />

type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Text Formatter" />




















providerName="System.Data.SqlClient" />











contract="DigiPanServices.ServiceContracts.IUsers" />


contract="DigiPanServices.ServiceContracts.IRankingAndScoring" />





openTimeout="10:01:00" receiveTimeout="10:01:00" sendTimeout="10:01:00"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" >
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />


















Regex for Valid Date

///
/// Checks the valid date.
///

/// The user.
public static bool CheckValidDate(DateTime date)
{
DateTime dt;
bool isValid = DateTime.TryParse(date.ToString(), out dt);

if (!isValid || dt.Year < 1753 || dt.Year > 9999)
{
return false;
}
else
{
return true;
}
}

Regex for Alphabet

public static bool IsAlphabet(string temp)
{
bool isAlpha = true;
Regex regularExp = new Regex(@"^([a-zA-Z]{1})$");
if (!regularExp.IsMatch(temp))
{
isAlpha = false;
}
return isAlpha;
}

Regex for Valid Decimal

// The value should be in the Format 0.00 for this use below method
///
/// Determines whether [is valid decimal] [the specified temp].
///

/// The temp.
///
/// true if [is valid decimal] [the specified temp]; otherwise, false.
///

public static bool IsValidDecimal(string temp)
{
bool isValidCurrency = true;
Regex regularExp = new Regex(@"^\d{0,9}(\.\d{1,2})?$");
if (!regularExp.IsMatch(temp))
{
isValidCurrency = false;
}
return isValidCurrency;
}

Regex for valid currency

///
/// Determines whether [is valid currency] [the specified temp].
///

/// The temp.
///
/// true if [is valid currency] [the specified temp]; otherwise, false.
///

public static bool IsValidCurrency(string temp)
{
bool isValidCurrency = true;
Regex regularExp = new Regex(@"^([0-9]{1,16}(.[0-9][0-9]))?$");
if (!regularExp.IsMatch(temp))
{
isValidCurrency = false;
}
return isValidCurrency;
}

Example of Static class, Extension methods, Comma Sepated Integers and Check String for Interger

When ever we want create a extension methods, the class should be static.
This example describes how is static class, how to write Extension methods.
We have two regex values one for checking comma sepated integers and checking for the integer.
public static class ValidationHelper
{
const string m_pattern = "^([0-9]*)$"; or ("\d+")
public static bool CheckString(this string str)
{
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(m_pattern);
return (r.Match(str).Success);

}
public static bool CheckCommaSepateIntegers(this string commastrinrg)
{
System.Text.RegularExpressions.Regex cerficateverify = new System.Text.RegularExpressions.Regex(@"^\d+(,\d+)*$");
return (cerficateverify.Match(commastrinrg).Success);
}
}