Friday, November 13, 2009

PDF Fails to open in IE

Actually I was trying to (open/Save As) a pdf file from the IE with SSL (HTTPS) ON,using the report viewr (RDLC). Fortunately it works fine with firefox and not in IE :(. Here is the deal, remove the Cache statement from the below code you are done :).
To know more about the issue please visit this link.

1: Response.Clear();
2: Response.Buffer = true;
3: Response.ContentType = "application/pdf";
4: Response.Cache.SetCacheability(HttpCacheability.NoCache);
5: Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
6: Response.Charset = "";
7: Response.BinaryWrite(pdfContent);
8: Response.End();

Friday, November 6, 2009

.Net Application Development Best Practices

Recommendations for building Highly Available .Net application

Cross cutting related

1.Consider Vertical and Horizontal partitioning of the application logic into layers and tiers, application having independent presentation, business and data layer is essential to build highly scalable and available application
2.Consider Internet Information Server (IIS) 7.0 and above at Web Server and app server tier, Windows Server 2008 as Server Operating System, SQL Server 2005 or higher for Databases
3.Take special care while selecting 3rd party components in the application architecture, usually not appropriately tested components can cause memory, security leaks leading to main application down. e.g. ODP.Net driver version 10.2.0.2.1 causes memory leak issues when used in .Net application. Check and use version which is latest and appropriately tested.
4.Design self healing applications, applications which log data and based on type of error and knows how to recover without administrator intervention.
5.Select logging, tracing and exception management framework which logs correct and useful information. Enterprise Library blocks can be considered for the same. Always provide graceful code exits than aborts.
6.Ensure code review is done for the complete application and standards, best practices are adhered to. No infinite loops, and avoid recursion logic.
7.As far as possible use the namespaces, apis, controls, components available OoB with framework than trying to implement same functionality through user defined programs
8.Thoroughly Test application for security attacks like SQL injection, Denial of service attacks
9.Ensure and plan for soft and hard memory growth with increase in number of users.
10.Ensure software releases, service packs are appropriately tested before rolling out in production.
11. Ensure appropriate latest antivirus software's are installed in the environment
12.Provide appropriate page security using transport security (https), data encryption using encryption algorithms, secure user logins implement certificates using 3rd party security certificates like Verisign.
13.Design system for least access rights, low surface area.
14.Least access right means to run an application, it should need least amount of privileges. Low surface area means application will expose limited software surface area or endpoints which are accessible by other applications, possibly implement this by writing modular windows services.
15.Consider software and hardware firewalls, as far as possible place database server and application server behind firewalls in the order mentioned.
16.Conduct memory profiling, perfmon analysis for appropriate memory and security counters before releasing application into production

Presentation Layer

1.Consider using disconnected scenarios when applicable. Use MS Smart client - Composite Application Block.
2.While designing stateless applications, remember to disable view state of controls, pages.
3.Plan appropriate size aspx pages and avoid too many controls on the page. Split complex functionality into multiple pages, tabs to reduce page size loads.
4.Implement client side Java script validations and report errors at presentation layer itself for data inappropriateness without making server calls
5.Appropriately employ Ajax behavior in the application/pages. Ajax calls leads to increase in network calls.

Business Layer
1.Assign dedicated Application pool for application hosted in IIS
2.Provide Caching in the middle tier and presentation layer.
3. For Distributed Caching, use Velocity framework. For application level caching one can use EL Caching block. Refer this for more info. State server provides reliable cache than InProc.
4.Write deadlock free Database and Dotnet programs, use appropriate threading and monitoring, mutex mechanisms.
5.For long running or Human workflow, consider persisting Workflows. .Net 3.5 has persistence feature which is further improved in .Net 4.0 Windows Workflow.
6.Consider designing stateless WCF services using appropriate configuration parameters for singleton, state full, per session, etc.
7.Use connection, session and thread pools and set respective timeouts
8.As far as possible avoid invoking unmanaged code from .Net, if the need be ensure the unmanaged objects are released from memory
9.Microsoft Dublin, currently in beta can be considered as part of application server for hosting Windows Workflow, WCF, Workflow Services as it provides high availability, scalability, reliability by providing features for persistence, state management, monitoring, etc.
10.Consider .Net Configurations (xml) for driving application settings, as one doesn’t have to restart the application for changes to take place.
11.Consider Clustering, Load balancing for presentation, business logic and Database tier
12.If possible, consider separating stateless logic from state full and plan independent hosting for the respective ones. Consider application pool recycling for stateless sites.
13.Consider setting web garden for multi core CPUs. Number of cores = Maximum Worker processes
14. Consider Caching in the middle tier and presentation layer.
15. For Distributed Caching, use Velocity framework. For application level caching one can use EL Caching block. Refer this for more info.
16.Consider asynchronous communication (fire and forget) patterns for modeling long running transactions, workflows.
17. Appropriately close WCF proxy connections on client, also plan for exception conditions. Recommended practice is mentioned here
18.If not appropriately written, developer written threading logic can cause unexpected application behavior, hence write it only when necessary.
19. Avoid using GC.collect(), as .Net automatically schedules Garbage collection(GC) when memory pressure builds up, no need to force it, as and when GC happens all other operations are suspended.

Persistence Layer

1.Microsoft will stop supporting Oracle driver for .net from 4.0 onwards, if planning to use ODP.net, consider using driver for 11G and above.
2.Physically separate Reporting, data warehousing from real time OLTP data
3.Consider Partitioning (horizontal, vertical) Database.
4. Consider Database Replication options (transactional, merge, snapshot as applicable) for high Database availability.
5. Have appropriate Database archival and backup strategy
By no means this is an exhaustive list; please feel free to add points based on your experience.


Most of these points were collected from Infosys Microsoft blog. Thanks to Sudhanshu Hate for providing these wonderful lists.

MS Chart Control an easy implementation

Basically MS chart control is used to depict the domain data to be repesented in a graphiacl format, which eases the understanding of a user to analyse the domain data. The best simple example that strikes my mind is a sales manager looking at a campaign information of multiple years. Lets see some basics that drives to build a chart control.

Before we dive in to building a chart control lets understand some of the most important chart components that we make use of it in our development.
• Chart Series:
- A series is a related group of data points. Each series is associated with a
chart type
• Chart Area:
- The chart picture consists of one or more chart areas, which are rectangular
areas that are used to draw series, labels, axes, grid lines, tick marks,
and so on. Multiple series can be plotted in one chart area, depending on
the chart types involved.
• Legend:
- A legend for the Chart picture. There can be an unlimited number of legends
in a chart.
• Grid Lines:
- There are major and minor horizontal and vertical grid lines, which usually
occur in conjunction with tick marks
• Tick Marks:
- There are major and minor horizontal and vertical tick marks, which usually
occur in conjunction with grid lines.
• Plot Area:
- The plot area is the inner rectangular area within a chart area that is used
to plot series and grid lines. Labels, tick marks, the axis title, and so
on, are all drawn outside of the plotting area and inside the chart area.
The plot area can be set via the ChartArea.InnerPlotPosition property.
• Axis Label
- Label along an axis
• Axis Title
- The title of an axis
• Chart Picture
- The chart picture, is the entire image surface that is rendered by the Chart
control. It corresponds to the root Chart object.
• Value Label
- A special label that occurs for a data point, slightly offset from where the
point is plotted. It can be the data point's value or custom text.

Below image describes complete picture of all the components of a chart control.







Chart control in aspx page


<asp:CHART ID="aChart" runat="server" BackColor="White" Width="396px" Height="312px" BorderDashStyle="Solid" BackGradientStyle="TopBottom" BorderColor="Silver" BorderSkin-SkinStyle="None">
<legends>
<asp:Legend Docking="Bottom" TableStyle="Wide" IsTextAutoFit="true" Name="Default" BackColor="Transparent" Font="Trebuchet MS, 8.25pt, style=Bold"></asp:Legend>
</legends>
<series>
<asp:Series MarkerSize="9" BorderWidth="3" Name="CompliantSalesPerStoreDay" LegendText="Series User friendly name" ChartType="Line" BorderColor="180, 26, 59, 105" Color="#99FF33" IsValueShownAsLabel="false" XValueMember="Date[Property/Column[which holds the X axix data]" YValueMembers="Property/Column[which holds the y axix data]" ChartArea="ChartArea1" Legend="Default" YAxisType="Secondary"></asp:Series>
</series>
<chartareas>
<asp:ChartArea Name="ChartArea1" BorderColor="64, 64, 64, 64" BorderDashStyle="Solid" BackSecondaryColor="White" BackColor="White" ShadowColor="Transparent" BackGradientStyle="Center">
<area3dstyle Rotation="25" Perspective="9" LightStyle="Realistic" Inclination="40" IsRightAngleAxes="False" WallWidth="3"/>
<axisy LineColor="64, 64, 64, 64">
<LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
<MajorGrid LineColor="64, 64, 64, 64" />
</axisy>
<axisx LineColor="64, 64, 64, 64">
<LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
<MajorGrid LineColor="64, 64, 64, 64" />
</axisx>
</asp:ChartArea>
</chartareas>
<Titles>
<asp:Title Name="Display Execution"></asp:Title>
</Titles>
</asp:CHART>

Some of the important Properties programmatically

//For setting the tool tip
aChart.Series["Seriesname"].ToolTip = "TooltipText";

//Making Visible/Invisible legend information
aChart.Series["Seriesname "].IsVisibleInLegend = false;

// Enable X axis margin
aChart.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = true;

// Enable 3D, and show data point marker lines
aChart.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = false;

//Enabling the secondary axis and axix title
aChart.ChartAreas[0].AxisY2.Enabled = AxisEnabled.True;
aChart.ChartAreas[0].AxisY2.Title = "SecondaryAxisTitle";
aChart.ChartAreas[0].AxisY.Title = "YAxixTitle";

//Set Y axis labels format
aChart.ChartAreas["ChartArea1"].AxisY2.LabelStyle.Format = "C2";


//Setting axis labes and intervals
aChart.ChartAreas["ChartArea1"].AxisY2.Minimum = 00.0;
aChart.ChartAreas["ChartArea1"].AxisY2.Maximum = maxY2AxixValue;
aChart.ChartAreas["ChartArea1"].AxisY2.Interval = intervalValue;
aChart.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
aChart.ChartAreas["ChartArea1"].AxisY.Maximum = 1;

//aChart.ChartAreas["ChartArea1"].AxisY.LabelStyle.Format = "0:0%";
aChart.ChartAreas["ChartArea1"].AxisY.LabelStyle.Format = "P2";

// Enable all elements
aChart.ChartAreas["ChartArea1"].AxisX.MinorGrid.Enabled = false;
aChart.ChartAreas["ChartArea1"].AxisX.MinorTickMark.Enabled = true;
aChart.ChartAreas["ChartArea1"].AxisX.MinorGrid.LineColor = Color.Silver;

// Set Title font
aChart.ChartAreas["ChartArea1"].AxisY.TitleFont = new Font("verdana", 8, FontStyle.Bold);
aChart.ChartAreas["ChartArea1"].AxisY2.TitleFont = new Font("verdana", 8, FontStyle.Bold);

// Set Title color
aChart.ChartAreas["ChartArea1"].AxisY.TitleForeColor = Color.Navy;
aChart.ChartAreas["ChartArea1"].AxisY2.TitleForeColor = Color.Navy;

aChart.Series["CompliantCurrent"]["ShowMarkerLines"] = "True";
aChart.Series["CompliantPrior"]["ShowMarkerLines"] = "True";

// Set new legend text font
aChart.Legends["Default"].Font = new Font("Verdana", 8, FontStyle.Regular);

// Set the legend title to Black
aChart.Legends["Default"].ForeColor = Color.Black;

// Set the alignment of the legend title
//aChart.Legends["Default"].Alignment = StringAlignment.Center;

// Disable axis labels auto fitting of text
aChart.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = false;

// Set axis labels font
aChart.ChartAreas["ChartArea1"].AxisX.LabelStyle.Font = new Font("verdana", 7, FontStyle.Bold);
aChart.ChartAreas["ChartArea1"].AxisY.LabelStyle.Font = new Font("verdana", 7, FontStyle.Bold);
aChart.ChartAreas["ChartArea1"].AxisY2.LabelStyle.Font = new Font("verdana", 7, FontStyle.Bold);

// Set axis labels angle
aChart.ChartAreas["ChartArea1"].AxisX.LabelStyle.Angle = 30;

// Disable offset labels style
aChart.ChartAreas["ChartArea1"].AxisX.LabelStyle.IsStaggered = false;

// Enable X axis labels
aChart.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = true;

// Enable AntiAliasing for either Text and Graphics or just Graphics
aChart.AntiAliasing = AntiAliasingStyles.All;

//This basically contolls the look of a chart image
aChart.BorderSkin.SkinStyle = BorderSkinStyle.None;
//Setting Line annotation to chart control this feature
annotation.AnchorDataPoint = point;
annotation.Height = -35;
annotation.ResizeToContent();
annotation.LineWidth = 3;
annotation.ToolTip = "Target Start date:" + dateTime.ToShortDateString();
annotation.LineColor = Color.Green;
annotation.StartCap = LineAnchorCapStyle.None;
annotation.EndCap = LineAnchorCapStyle.None;
aChart.Annotations.Add(annotation);

//Finding Maximum point for the Y axis
//chartData is a list which contains all the series data

decimal? maxValueOfSeries = chartData.Max(c => c.YaxisSeriesName);
var findMax = new List
{
maxValueOfSeries
};
decimal? maxSecondaryAxisValue = findMax.Max();
if (maxSecondaryAxisValue.ToString().Contains("."))
maxSecondaryAxisValue = maxSecondaryAxisValue + 1;

//For the five intervals : Increase it if the interval is more than 5
var secondaryY2AxisIntervalValue = (double)(maxSecondaryAxisValue / 5);

//Note: In any case if the X axis values are set to date and in order to //retrieve the date values, following conversion is required, basically the //the dates are stored in double format.
//Convert Double to DateTime.
DateTime dateTime = DateTime.FromOADate(point.XValue);


Following are the Settings that needs to be entered in the web.config file.
Place them at appropriate level as seen in the enclosed tags.

<appSettings>
<add key="ChartImageHandler" value="storage=file;timeout=20;url=~/website/temp/TempChartImages" />
//Setting Relative path [Create a folder “TempChartImages” in the above defined path]
</appSettings>

<handlers>
<add name="ChartImageHandler" preCondition="integratedMode" verb="GET,POST,HEAD" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
<httpHandlers>
<add path="ChartImg.axd" verb="GET,POST,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<pages><controls>
<add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>

With this you are done with implementing a chart control.

Download Link: http://www.microsoft.com/downloads/details.aspx?FamilyId=130F7986-BF49-4FE5-9CA8-910AE6EA442C&displaylang=en