Tuesday, March 12, 2013

Embedded Code and Inline Server Tags

Embedded Code and Inline Server Tags

Introductions
Hi, I hope it will be  more useful , so we will talk about  something we need to use every day in coding ,we will talk about  "Embedded Code " using "In line Server Tags " . Briefly it used to write server side code somewhere where it not allowed directly . more developers use it in data binding controls .but you can use it in many Places Like (Java Script , CSS , ASPX ) , and you can use it with Routing ,ConnectionStrings , XMLQuery , AppSettings , Recourses Files or just writing server side code mixed with html.  my be you had seen it in the top of .aspx  page .OK ! Let us  begin .
What In line Server Code is ?
inline server code enables you to embedded server side code mixed with client script like javascript or mixed with aspx or with css as we mentioned before.
What Is In line Server Tags ?
Look at this :
<%      %>
these tags what we talk about. It comes from ASP classic style and it used in PHP and JSP too for the same reason "Writing Server Side Code ".
Note: you must know that we can't use it in code behind (Page.aspx.cs ) .
inline Code and  Page Life cycle :
When the page call its Render Method after the PreRenderComplete Event completed the compiler will Execute this Code and embedded it into Render method which accept HtmlTextWriter  as a single parameter  like the following :
protected override void Render(HtmlTextWriter writer)
 {
     base.Render(writer);
}
Let us see the forms you may have seen:
 Page Directive
<%@ Page Language="C#"  %>
Rendering Code
<% Response.Write("Hello World!");  %>
<%= SayHello("Ahmed") %>
<%: DateTime.Now.ToString()  %>
Expression Syntax
<%$ ConnectionStrings:ConnStrFromWebConfig  %>
<%$ AppSettings:ValueFromWebConfig  %>
<%$ Resources:Resource, Arabic  %>
<%$ RouteValue:year  %>
<%$ YourExpressionPrefix : Any   %>
Data Binding  Syntax
<%# Eval("Name")  %>
<%# Bind("Name")  %>
<%# XPath ("Name")  %>
Comment Server
<%-- <asp:Label runat="server" Text="Label"></asp:Label>-- %>
Let us do it in details :
Directive
We use directive to specify settings used by page and user control Compiler . we use it to say hi complier this file is ...... .each directive can have number of attributes as you need.
each directive start with @ . ASP.Net introduced number of Directive as following :

@Page
: used on .aspx files only and you can use only one  directive inside a file .

<%
@ Page Language="C#" %>
<%@ Page Language="C#" CodeFile="Default2.aspx.cs" Inherits="Default2"  %>
Note that we are  using Codefile to pass the file name of code behind and inherits to pass class Name.

@Control : used only in .ascx files (user control)
<%@ Control Language="C#" ClassName="WebUserControl"  %>

@Import :  used for name space declaration and only when we write code inside script tags,I mean that if we use code behind we don't need it because we will use "Using Directive" (C#) or " Imports " (VB.net)
<%@ Import Namespace="System.Data"  %>

@Assembly :  used to Links an Assembly(.DLL or .CS and .VB ) to that page and user control .
DLL files like this
<%@ Assembly Name="CustomFile"  %>
(without .dll extension )
Class files like this :
<%@ Assembly src="Csharp.cs"   %>
<%@ Assembly src="Csharp.vb"   %>
Note: we are using Name attribute with dll files and src with class files.

@Register : used to register Controls (User Controls and Custom Server Controls) to page and user control.
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp"  %>
<%@ Register src="WebUserControl.ascx"   tagname="WebUserControl" tagprefix="uc1"  %>

Note :we are using Name attribute when using assembly and using src when user control.
@Implements : used when we want to implement an Interface . and this Directive  takes only one attribute "Interface" .
<%@ Implements Interface="IWebParts"  %>

@Reference : used to indicate that the source file of the page or user control  should dynamically compiled and linked to the current page .
<%@ Reference Control ="~/WebUserControl.ascx"  %>
<%@ Reference Page="~/Default2.aspx"  %>
<%@ Reference VirtualPath ="anyfile.any"  %>

@OutPutCache : used when we need to put a page or user control in the cache.
<%@ OutputCache Duration ="900" VaryByParam ="none"  %>
Note: both attributes ( Duration and VarybyParam ) are required .

@Master : used to decalre page as Master page.
<%@ Master Language="C#"  %>

@MasterType : used to reference Master Page when we need to access master page through  Master Property .
<%@ MasterType VirtualPath ="~/MasterPage.master"   %>

@PreviousPage : used when need to access previous page through PreviousPage Property .
<%@ PreviousPageType VirtualPath ="~/Default4.aspx"   %>

@Application : used to declare the global application file .(global.asax)
<%@ Application Language="C#"   %>

@WebService : used to declare the web service file .(.asmx)
<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService"   %>

@WebHandler: used to declare the generic handler file (.ashx)
<%@ WebHandler Language="C#" Class="Handler"  %>

@ServiceHost : used by WCF (Windows Communication Foundation) .
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>

Rendering Code
Render code tags like Response.write Method. Here an example : using for Looping
    <div>
         <% for(int i = 0 ; i <5; i++){  %>
             Hello World ! <br />
           <%  } %>
    </div>
output the following :
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
 you can use it to execute a method but this time we use " = " to get out of Response.write to an Expression and =  is used to resolve an expression and return its value to the block
<%@ Page Language="C#"   %>
<script runat="server">
    string message = "I Can Do it ";

    string SayHello(string name)
    {
        return "Hello  " + name;
    }   
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test Page </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <%= SayHello("Ahmed") %>         <br />
         <br />
         <%="Message variable = " + message %>    </div>
   </form>
</body>
</html>
it will output string say "Hello Ahmed " and also gets the value of message variable .
Note : this code blocks render nothing (no html controls ) . try it yourself . browse this code in the browser and Right click to View source .
It provides a concise way to automatically HTML encode content and then render it as output
  <%:DateTime.Now.ToString () %>
You can learn more here :
we can also use it to embedded Server Side code in Client Side Code (Java Script)
what about calling Server side Method from Client Side Method . Let us do it :
take a look at this code
<%@ Page Language="C#"   %><script runat="server">
    string SayHello(string name)
    {
        return "Hello  " + name;
    }   
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test Page </title>
    <script type="text/javascript" >
        function SayAny() {
            alert(' <%= SayHello("ahmed") %>');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <br />
        <input type="submit" onclick="SayAny()" value="Say Hello" />
        <br />
    </div>
    </form>
</body>
</html>
 it do what you expect : showing alert message .

Sometimes we have a problem when passig control id to client side code like this
var txt = document.getElementById("TextBox1");
and this happened when we work with container like master page or when we want to find control inside Data contorls Like GridView ,DataList ,Repeater ,and so on. this happens because the control has been changed to something like "container_ControlId". and to solve this issue we can use server side blocks like the following :
var txt = document.getElementById("<%=TextBox1.ClientID %>");
you can use alert message to display the value of this TextBox like this :
alert(txt.value);
Expression Syntax :
Get Connection String Section :
<%$ ConnectionStrings:ConnStrFromWebConfig %>
after we set connection strings in web.config file then we need to use data source controls ,Like the following :
Example
<asp:SqlDataSource ID="SqlDataSource2"   runat="server"  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="SELECT * FROM [Categories]">
</asp:SqlDataSource>
Notice: connectionstring is the name of connection string section inside Web.Config Like following :
Web.config :
<connectionStrings>
    <add name="ConnectionString"
            connectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;
                                        Integrated Security=True;User Instance=True"
            providerName = "System.Data.SqlClient" />
 </connectionStrings>
Get AppSettings Section
<%$ AppSettings:ValueFromWebConfig %>
after we set AppSettings section in web.config file you can call it using key name to return its value .

Web.config

<appSettings>
        <add key ="KeyName" value ="This Value Is Ahmed"/>
</appSettings>
Default.aspx
<asp:Label Text="<%$ AppSettings :Keyname  %>" runat="server" />
Get a value from Global Resource File (.resx )
<%$ Resources:Resource, Arabic  %>
Let us take an example switching between two Language (Arabic and English ).
  • Create two files (Resource.resx , Resource.ar-eg.resx ) and put them in App_GlobalResources folder.
  • Define a key with name "Greeting" in both resource files.
              Note : the "greeting" key will have two different value for Arabic and English .
  • Create test page.aspx and drag a label control and drop down list control. so ,your aspx code will be like this :
<div>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
       <asp:ListItem Value="ar-eg">Arabic</asp:ListItem>
       <asp:ListItem Value="en-us">English</asp:ListItem>
    </asp:DropDownList>
    <br />
    <br />
    <asp:Label ID="Label1" runat="server" Text="<%$ Resources:Resource, Greeting %>"> </asp:Label>   
</div>
Note :
- Resources >> Say " I am working with resource files ".
- Resource >> say "I am the resource file name without extension".
- Greeting >> say " I am the Key which my value will be displayed"
now we have two values for "Arabic" and "English" we can switch between them. what will happen if we select English or Arabic ? ok, we need some code to change Language and Current Culture .let us go to next step:
  • We need to override IntializeCulture Method as following :
protected override void InitializeCulture()
    {
        if (Request["DropDownlist1"] != null)
       {
            string lang = Request["DropDownlist1"];
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(lang );
            Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture(lang );
        }
    }
Now you can select your Language from drop down list control and see that the related content will be displayed.
Routing
ASP.Net Routing is something about mapping URLs, Routing is available in ASP.Net web forms and ASP.Net MVC.Since .net framework 3.5. to use routing you need to create static method that take a parameter of RouteCollection data type inside global.asax file, then call these method in Application_Start event .
May you need more in Routing  so here you can take a look
Ok , what we want to say is we can use Expression Syntax to set URLs Like this :
<%$ RouteUrl:action=Edit , CategoryName=Cars%>
<%$ RouteValue:year %>
You need to understand what action and categoryName means? To do this refer to The above Link .
Exrpression Builder
<%$ YourExpressionPrefix : Any   %>
yes ,  you can create your Expression like mine : <div>   <asp:Label Text="<%$ myCode:DateTime.Now %>" runat="server" /></div>
to learn more about Expression Builder Click Here
Data Binding Syntax
<%# Eval("Name") %>
<%# Bind("Name")%>
<%# XPath ("Name") %>
We use embedded code in Data binding to set or get or in Other words to read and write to a data source .we have Two methods for  working with Data base (Eval and Bind ) and one for working with XML (XPath that stand of xml path ) .so , what is the different between Eval and bind ? Eval method is One way that means it is for reading and Bind method is Two way that means it is for Reading and writing  .
Example :  using eval method in grid view to display Images .
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Image ID="Image2" runat="server" ImageUrl='<%# Eval("Path")  %>' Width="70" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
In the above example we use eval method to get path field from data base and pass It to ImageUrl Property.
try to use bind method in editing data.
XPath method:
Use it when working with Xml, we can use it to select element or attribute and get its value and it comes in many forms Like this :
Look at this file.xml. we use it to simplifies the following :
<?xml version="1.0" encoding="utf-8" ?>
<Links>
    <Link>
       <name>Microsoft</name>
       <Site>http://www.microsoft.com</Site>
   </Link>
   <Link>
       <name id="10" >Asp.net</name>
       <Site>http://www.asp.net</Site>
   </Link>
    <Link>
        <name id="20" >MSDN</name>
        <Site>http://www.msdn.com</Site>
    </Link>
</Links>   
<%# XPath ("Name") %>
get the value of the Name element .
output here will be as following : Microsot  ASP.Net  MSDN
<%# XPath("name[@id]") %>
Get the value of the name element which take an attribute  with name "Id"
output here will be as following : ASP.Net  MSDN
<%# XPath ("name[@id=\"10\"]") %>
Get the value of name element which take an attribute with name id that its value equal 10 .

output here will be as following : ASP.Net 
<%# XPath("name/@id") %>
Get the value of  Every  attribute which its name is 'id' that  was defined in "name" element .
output here will be as following : 10  20
Yes, it is give xml more funs .
Note :
When using your custom method as Binding Expression Remember to call Databind Method . this question I meet it in Asp.Net forums and that is my answer "call Databind method to that control "
Example : Get Text  from the result of custom method .
<div>
      <asp:Button ID="SomethingBtn" Text="<%# ServerSideMethod()  %>" runat="server" />
</div>
So when we try to view it in browser the button wouldn't display any text . because we need to call Data bind method for that button Like this :
protected void Page_Load(object sender, EventArgs e)
    {
        Somethingbtn.DataBind();
    }
And finally I want to say that you can use all or one of them Like this :
<%# Eval("Id","~/default.aspx?id={0}")  %>
<%# "Your Name Is :" + Eval("Name") %>
<%# SayHello( Eval("Name").ToString () ) %>
And More ...........
Last thing is Comment Server 
We can use it to put  a comment where the comment is not allowed  .
Example :
<div>
<%-- <asp:Button ID="Button2" runat="server" Text="Button"  />--%>
</div>

Transpose Row into Column in SQL Server 2008

private DataTable GenerateTransposedTable(DataTable inputTable)
    {
        DataTable outputTable = new DataTable();

        // Add columns by looping rows

        // Header row's first column is same as in inputTable
        outputTable.Columns.Add(inputTable.Columns[0].ColumnName.ToString());

        // Header row's second column onwards, 'inputTable's first column taken
        foreach (DataRow inRow in inputTable.Rows)
        {
            string newColName = inRow[0].ToString();
            outputTable.Columns.Add(newColName);
        }

        // Add rows by looping columns       
        for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
        {
            DataRow newRow = outputTable.NewRow();

            // First column is inputTable's Header row's second column
            newRow[0] = inputTable.Columns[rCount].ColumnName.ToString();
            for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
            {
                string colValue = inputTable.Rows[cCount][rCount].ToString();
                newRow[cCount + 1] = colValue;
            }
            outputTable.Rows.Add(newRow);
        }

        return outputTable;
    }

Friday, March 1, 2013

CRYSTAL REPORT DESIGN CONCEPT


CRYSTAL REPORT DESIGN CONCEPT

This section describes the basic concepts of report design and helps you decide what information you want to include in your report.
Basic report design
The purpose of this section is to suggest a structured approach to preparing a Crystal report. This approach includes the following elements:
  • Deciding on the content of the report.
  • Developing a prototype on paper.
This section has been designed to provide a conceptual understanding of the reporting process

What is the overall purpose of the report?

Reports are management tools. Their purpose is to help you quickly grasp the essential elements and relationships found in raw data, to help you make effective decisions. For a report to be effective, it has to present the correct data in a logical way. If it presents the wrong data, or if it presents the right data in a haphazard manner, the report may slow the decision-making process or may even encourage incorrect decisions.
A good starting place in the development of a report is to write out the purpose of the report in a sentence or two. The purpose statement helps you focus on your primary needs, and it gives the report both a starting point and a goal.
Here are some examples of purpose statements.
  • The purpose of this report is to show monthly and year-to-date sales by sales representatives, compare this year's numbers to last year's, and flag representatives whose sales figures do not meet company standards.
  • The purpose of this report is to show sales activity for each item in inventory, and to suggest reorder quantities based on that activity.
  • The purpose of this report is to calculate bowling averages and handicaps for each member of the bowling league.
Defining the purpose of the report before you start is a critical step in the overall process.

Who is going to read the report?

A single report is often used by many individuals. A detailed, company-wide sales report, for example, may be used by sales representatives, the regional sales manager, the national sales manager, and the Chief Operating Officer (COO).
These individuals will be interested in different aspects of the report:
  • A sales representative will use the report to evaluate individual sales performance and compare this performance to that of other representatives in the region.
  • The regional sales manager will use the report to evaluate regional representatives and compare the region's performance to that of other regions.
  • The national sales manager will use the report to evaluate the performance of regional managers and compare overall sales to the current sales forecasts.
  • The COO will use the report to evaluate the performance of the Vice-President of Marketing and the sales department as a whole, and to project such things as manufacturing needs and warehouse locations.
Since each user of the report has different interests, it is important to plan the report so it includes the information each user is looking for.

Determining the layout of the report

What is the report title going to be?

Write out a working title for the report. You may decide to change it later, but at least you will have a title to use when creating the prototype report.

What identifying information is needed in the header and footer?

You may wish to include the print date, information on who prepared the report, a block of text to describe the purpose of the report, the range of data covered, or something similar. If you are going to include such information, write it down so you can use it in preparing your prototype.
The information can come from a variety of sources, depending on the kind of information you plan to use.
  • Information on who prepared the report might be drawn from individual data fields in the database table(s) used. If it is to be drawn from a database table, what table? Or, what combination of tables?
  • A block of text can be created as a text object and placed anywhere on the report.
  • Crystal Reports can generate information such as the print date or page numbers.

Finding the data

What data do you want to use in the report?

Do you know the type of database you are reporting from? Will you be reporting off a data file, SQL/ODBC, a Business View, or a Dictionary?
If you do not know, ask the database administrator in your organization for help in setting up the database type and location of the data. For more information,
Are you familiar enough with the data to find the necessary information? When looking for a Customer Contact name, can the field be found in a database table?
If not, your MIS professional, database administrator, or co-workers will have to help you become familiar with the data.

What specific data should appear in the body of the report?

The body should contain all the data needed to fulfill the statement of purpose you wrote for the report. It should also contain all of the data needed by the various users that you have identified.
This step requires you to look at the available database table(s). Crystal Reports allows you to combine data from different databases when you create reports, so you have a great deal of flexibility in your work.
  • Much of the data in a typical report is taken directly from data fields. Which data fields will be used, and where are they located?
  • Other data will be calculated based on data fields. Which data fields will be used in the calculations?
  • Still other data will be placed directly into the report using text objects (headings, notes, labels, and so on).

Does the data exist or does it need to be calculated?

Some report information can be drawn directly from data fields (sales information, for example); other information will have to be calculated based on data field values (for example, sales commission, based on the relationship of sales to quota). In your planning, it can be helpful to segregate or flag data that needs to be calculated from that which can be used directly.

What types of fields contain data?

You should take the time to get to know the data type for data fields that will be used in your calculations. Since formula functions and operators work with specific kinds of data, it is important to recognize the data type you are working with, before you start any calculations. For example, some functions require numeric data, while others work with only string fields. For more information on specific functions and operators, search for "Functions" and "Operators," or for the function or operator by name in the Crystal Reports online help.

Do you want the data organized into groups?

How? By customer? By date? By hierarchy? Or by other criteria? Crystal Reports provides several options for grouping data in a report.

Do you want the data sorted based on record or group values?

Crystal Reports gives you both alternatives.

Do you want the report to contain only specific records or groups?

Crystal Reports gives you the opportunity to base a report on all records in a given database, or on a limited set of records from the database. Crystal Reports can be used to select records based on simple date ranges or comparisons, or to create complex formulas to identify the records to be included. Take a few minutes to determine the records needed for the report and list the criteria to be used for selecting those records.

Do you want to summarize the data?

Do you want to total, average, count, or determine the maximum or minimum value included in all the values in any column on the report?
Crystal Reports allows you to do this, and it also allows the grand total (or the grand total average, grand total count, and so on) to be placed at the bottom of the selected column.

What information should be flagged on the report?

You may want to call attention to some data by flagging it on the report. For example, non-moving inventory items are often flagged on inventory reports so they can be given special attention. You might want to flag each item that has shown no activity during the last month, during the last three months, or during some other defined period. To flag information, identify it and any conditions that will trigger the flagging.

How do you want information flagged?

You may want to flag items with an asterisk or some other symbol, or you may want a word to appear as a flag. In any case, you should write out flagging instructions so they are handy.
Crystal Reports gives you the opportunity to underline report elements, and change the font type, size, or color used for specific report items. It allows you to put borders around items and to draw lines and boxes (to break the report into sections), set off headings, and so on. All of these formatting tools can be used to highlight key data on a report.

Determining printing area characteristics

Each report area has its own printing characteristics. It is important to understand these characteristics because they affect when and how often different report objects get printed.

In what order will the areas print on the report?

Areas print in the order they appear on the Design tab (top to bottom). If there is more than one section in an area, the sections print in the order they appear. For example, if you have three Report Header sections, all three of those sections will print, in order, before the section(s) in the Page Header area begin to print.

How often do report objects print?

The way objects print will determine how you design your report. This will help you decide where to place charts, Cross-Tabs, and formulas to get specific results.
Report Header
Objects placed in the Report Header area print once, at the beginning of the report.
  • Charts and Cross-Tabs placed in this area contain data for the entire report.
Note:    Both charts and Cross-Tabs can filter report data by using a Group Sort; in such cases, the data shown in the chart or Cross-Tab is a subset of the data for the entire report.
  • Formulas placed in this area are evaluated once, at the beginning of the report.
Page Header
Objects placed in the Page Header area print at the beginning of each new page.
  • Charts or Cross-Tabs cannot be placed in this section.
  • Formulas placed in this area are evaluated once per page, at the beginning of each new page.
Group Header
Objects placed in the Group Header area print at the beginning of each new group.
  • Charts and Cross-Tabs placed in this area contain data just for the group.
  • Formulas placed in this area are evaluated once for each group, at the beginning of the group.
Details area
Objects placed in the Details area print with each new record.
  • Charts or Cross-Tabs cannot be placed in this area.
  • Formulas placed in this area are evaluated once for each record.
Group Footer
Objects placed in the Group Footer area print at the end of each group.
  • Charts and Cross-Tabs placed in this area contain data just for the group.
  • Formulas placed in this area are evaluated once for each group, at the end of the group.
Report Footer
Objects placed in the Report Footer area print once at the end of the report.
  • Charts and Cross-Tabs placed in this area contain data for the entire report.
Note:    Both charts and Cross-Tabs can filter report data by using a Group Sort; in such cases, the data shown in the chart or Cross-Tab is a subset of the data for the entire report.
  • Formulas placed in this area are evaluated once, at the end of the report.
Page Footer
Objects placed in the Page Footer area print at the bottom of each page.
  • Charts and Cross-Tabs cannot be placed in this area.
  • Formulas placed in this area are evaluated once per page, at the end of each new page.

Developing a prototype on paper

While a paper prototype is useful regardless of your level of expertise with Crystal Reports, it is particularly valuable when you are first learning the program. With the paper prototype in hand, you can put your full effort into learning and using the commands, rather than into trying to design and learn at the same time.
To design a paper prototype
  1. Get the same size paper you will be using for the finished report.
  1. Position the title and other descriptive header information, using boxes or lines to represent report elements.
  1. Position the footer information.
  1. Review the page layout for balance.
  1. Look at the information you intend to include in the body of the report:
    • Count the number of fields being used and estimate the appropriate spacing between fields.
    • Use rectangles to pencil in the fields within the estimated spacing.
    • Change the spacing if you need to.
    • Decide on a logical sequence for presenting the data in the body of the report.
    • Label the fields to indicate that sequence.
  1. Use small boxes to indicate group values and totals.
  1. Place random flags in the column where you want flags to appear.
  1. Darken any elements you want highlighted to make them stand out from the rest of the prototype.
Review the finished product for layout and balance, and make changes as needed

ref: