Tuesday, May 26, 2009

Image Resize (on fly thumbnail image generation)

1)web.config


2)Create Folder called images (on application physical path)

3)Create .cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

///


/// Summary description for Lib
///

public class Lib
{
public Lib()
{
//
// TODO: Add constructor logic here
//
}


#region Thumbnail Functions
public bool ThumbnailCallback()
{
return false;
}


private float DeterminePercentageForResize(int height, int width)
{
int highestValue;
if (height > width)
highestValue = height;
else
highestValue = width;

float percent = (float)int.Parse(ConfigurationManager.AppSettings["ThumbSize"].ToString()) / (float)highestValue;

if (percent > 1 && percent != 0)
throw new Exception("Percent cannot be greater than 1 or equal to zero");
else
return percent;
}

private static System.Drawing.Image FixedSize(System.Drawing.Image imgPhoto, int Width, int Height)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;

float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;

nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((Width -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((Height -
(sourceHeight * nPercent)) / 2);
}

int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(Width, Height,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.White);
grPhoto.InterpolationMode =
InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(imgPhoto,
new Rectangle(0, 0, destWidth, destHeight),
new Rectangle(0, 0, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);



grPhoto.Dispose();
return bmPhoto;
}

public bool SaveAsThumbnail(string largeimage)
{
bool status = false;
try
{
string strPathPrefix = ConfigurationManager.AppSettings["UploadPrefix"].ToString();
string strPath = ConfigurationManager.AppSettings["UploadLocation"].ToString();

string strFilename = System.IO.Path.GetFileNameWithoutExtension(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
string strThumbnail = strFilename + "_small.jpg";

int intThumbnailSize = int.Parse(ConfigurationManager.AppSettings["ThumbSize"].ToString());
int intWidth, intHeight;
Bitmap photo;

try
{
photo = new Bitmap(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
}
catch (ArgumentException)
{
throw new HttpException(404, "Photo not found.");
}

if (photo.Width > intThumbnailSize)
{
if (photo.Width > photo.Height)
{
intWidth = intThumbnailSize;
intHeight = photo.Height * intThumbnailSize / photo.Width;
}
else
{
intWidth = photo.Width * intThumbnailSize / photo.Height;
intHeight = intThumbnailSize;
}
}
else
{
intWidth = photo.Width;
intHeight = photo.Height;
}

System.Drawing.Image imgPhotoVert = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
System.Drawing.Image imgPhoto = null;

imgPhoto = FixedSize(imgPhotoVert, intWidth, intHeight);
imgPhoto.Save(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + strThumbnail), ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPhotoVert.Dispose();
photo.Dispose();
status = true;

}
catch (Exception ex)
{
//AppLogger.LogError("SaveAsThumbnail(): " + ex.Message, AppLogger.Severity.Error);
ex.Message.ToString();
}

return status;
}

public bool SaveAsImage(string largeimage, int ResizeImageSize, string FileNameRef)
{
bool status = false;
try
{
string strPathPrefix = ConfigurationManager.AppSettings["UploadPrefix"].ToString();
string strPath = ConfigurationManager.AppSettings["UploadLocation"].ToString();

string strFilename = System.IO.Path.GetFileNameWithoutExtension(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
string strThumbnail = strFilename + "_" + FileNameRef + ".jpg";

int intThumbnailSize = ResizeImageSize;
int intWidth, intHeight;
Bitmap photo;

try
{
photo = new Bitmap(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
}
catch (ArgumentException)
{
throw new HttpException(404, "Photo not found.");
}

if (photo.Width > intThumbnailSize)
{
if (photo.Width > photo.Height)
{
intWidth = intThumbnailSize;
intHeight = photo.Height * intThumbnailSize / photo.Width;
}
else
{
intWidth = photo.Width * intThumbnailSize / photo.Height;
intHeight = intThumbnailSize;
}
}
else
{
intWidth = photo.Width;
intHeight = photo.Height;
}

System.Drawing.Image imgPhotoVert = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
System.Drawing.Image imgPhoto = null;

imgPhoto = FixedSize(imgPhotoVert, intWidth, intHeight);
imgPhoto.Save(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + strThumbnail), ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPhotoVert.Dispose();
photo.Dispose();
status = true;

}
catch (Exception ex)
{
//AppLogger.LogError("SaveAsImage(): " + ex.Message, AppLogger.Severity.Error);
ex.
}

return status;
}

#endregion
}

4).aspx/ascx


5).aspx.cs/.ascx.cs
on btn_click event
string strpPath = ConfigurationManager.AppSettings["UploadLocation"].ToString();
string strpPathPrefix = ConfigurationManager.AppSettings["UploadPrefix"].ToString();
string extenstion = DateTime.Now.ToString("ddMMyy-HHmm");
string filepath = "", strResizeFilename = "", strFullFilename = "";
bool ResizeImage = false;

Lib objlib = new Lib();

if (fPhotUpload.FileName != "")
{
if (fPhotUpload.HasFile)
{

if (fPhotUpload.HasFile)
{
filepath = extenstion + fPhotUpload.FileName.Replace(" ", "_");
strFullFilename = Server.MapPath(strpPathPrefix + strpPath) + filepath;
fPhotUpload.SaveAs(strFullFilename);
ResizeImage = objlib.SaveAsImage(filepath, Convert.ToInt16(ConfigurationManager.AppSettings["LargeThumbSize"]), "large");
}
if (ResizeImage == true)
{

strResizeFilename = System.IO.Path.GetFileNameWithoutExtension(filepath);
hdnbigimage.Value = strResizeFilename + "_large.jpg";


ResizeImage = false;
ResizeImage = objlib.SaveAsImage(filepath, Convert.ToInt16(ConfigurationManager.AppSettings["ThumbSize"]), "small");

if (ResizeImage == true)
{
strResizeFilename = "";
strResizeFilename = System.IO.Path.GetFileNameWithoutExtension(filepath);
hdnsmallimage.Value = strResizeFilename + "_small.jpg";
}
}
else
{
lblMsg.Text = "Image path cannot be found";
return;
}
}
}

Friday, May 22, 2009

Crystal Reports

CRYSTAL REPORT STEPS TO GENERATE:

1) "Add New Item" dialog box, select "Crystal Report" as the template, provide the name "SampleRpt01.rpt" and click on the "Add" button



2) Crystal Reports Gallery



3)Connect with DB.





Once the report gets added, you should be able to see the Visual Studio layout with "Field Explorer," the new "Crystal Reports" menu and an "Embedded Crystal Report Designer" with two modes ("Main Report" and "Main Report Preview" at the bottom) as shown below.



The "Field Explorer" can be used to drag and drop the columns onto the report, add new, add new tables to the report, add new formula oriented columns, running totals, and so on.

The report designer is initially divided into five sections (Report Header, Report Footer, Page Header, Page Footer and Details). Report Header gets displayed only on the first page. Report Footer gets displayed only on the last page. Page Header gets displayed on top of every page. Page Footer gets displayed at the bottom of every page. The Detail section is the body of the report where all of the rows get displayed.

Using the formatting toolbar, properties windows and tools in toolbox, we can format the report in the required manner. Try playing with formatting the report (and preview it simultaneously without executing the project).

Displaying Crystal Report on the ASP.NET 2.0 web page

To display the report on the web page, we need to work with Crystal Report Viewer control. The following are the steps required to attach the Crystal Report to the ASP.NET 2.0 web page:

Using the ToolBox, drag and drop the CrystalReportViewer control.

Using the Smart tag of the CrystalReportViewer control, select "New Report Source."

This leads you to a new dialog box, "Crystal Report Source." Every CrystalReportViewer gets associated with the CrystalReportSource control. You can directly drag and drop the CrystalReportSource control from the toolbox as well and assign the same in a smart tag. Provide the details and click OK.

The moment you hit OK, you should be previewing the report. Just hit F5 to execute your web site. Once the web page gets displayed, provide logon information for the report and click on "Logon."



using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)
{
ConnectionInfo ConnInfo = new ConnectionInfo();


{
ConnInfo.ServerName = ".sqlexpress";

ConnInfo.DatabaseName = "Northwind";

ConnInfo.UserID = "sa";


ConnInfo.Password = "eXpress2005";
}



foreach (TableLogOnInfo cnInfo in this.CrystalReportViewer1.LogOnInfo)
{

cnInfo.ConnectionInfo = ConnInfo;
}
}

//
/*
Directly bind the report to the viewr control on Page Load event

CrystalDecisions.CrystalReports.Engine.ReportDocument rd =
new CrystalDecisions.CrystalReports.Engine.ReportDocument();

rd.Load(Server.MapPath("CrystalReport.rpt"));
rd.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rd;
CrystalReportViewer1.DataBind();


*/

Pagination Custamization

Pagination Custamization:

1).aspx/.ascx Design View







2).aspx.cs/.ascx.cs


private int intCurrentselectPage;

#region CurrentselectPage
public int CurrentSelectPage
{
get
{
return intCurrentselectPage;
}
set
{
intCurrentselectPage = value;
}
}
#endregion


protected void grdNewsList_DataBound(object sender, EventArgs e)
{
if (grdNewsList.Rows.Count > 0)
{
GridViewRow gNavFooter = grdNewsList.BottomPagerRow;
LinkButton lbP = gNavFooter.FindControl("lbPrev") as LinkButton;
LinkButton lbN = gNavFooter.FindControl("lbNext") as LinkButton;
try
{
if (grdNewsList.PageIndex == 0)
{
lbP.Enabled = false;
}

int iStartIndex = 0;
int iCurrentPage = CurrentSelectPage + 1;

int iCalc = (iCurrentPage / 5) + ((iCurrentPage % 5) >= 1 ? 1 : (iCurrentPage % 5));

if (iCalc > 1)
{
iStartIndex = (((iCalc * 5) - 5) + 1);
}
else
{
iStartIndex = 1;
}

for (int i = 1; i <= 5; i++)
{
LinkButton lb = gNavFooter.FindControl("lb" + i.ToString()) as LinkButton;

lb.Text = iStartIndex.ToString();
lb.CommandArgument = iStartIndex.ToString();
if (iStartIndex > grdNewsList.PageCount)
{
lb.Visible = false;
}
if (iStartIndex == grdNewsList.PageIndex + 1)
{
lb.Enabled = false;
}
iStartIndex++;
}

if (grdNewsList.PageIndex == grdNewsList.PageCount - 1)
{
lbN.Enabled = false;
}
}
catch (Exception ex)
{
throw (ex);
}
}
}


protected void grdNewsList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
CurrentSelectPage = e.NewPageIndex;
grdNewsList.PageIndex = e.NewPageIndex;
DisplayFromListPublishedNews(); // Bind the Method again.
}

Thursday, May 21, 2009

Error Log

XML Format.

1)Create a .cs file.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using System.Text;


///


/// Summary description for AppLogger
///

public static class AppLogger
{
// Fields
private static XmlDocument LogDoc;
private static XmlElement LogElement;
private static XmlNode LogNode;

// Methods
static AppLogger()
{
try
{
LogDoc = new XmlDocument();
string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorFolder"] +"\\"+ DateTime.Now.ToString("dd-MM-yyyy") + ".xml");

if (!File.Exists(path))
{
XmlTextWriter writer = new XmlTextWriter(path, Encoding.Unicode);
writer.WriteStartDocument(true);
writer.WriteStartElement("LOGGER");
writer.WriteEndElement();
writer.Close();
}
try
{
LogDoc.Load(path);
}
catch
{

}
}
catch
{
}
}

public static void LogError(string Message, Severity severity)
{
try
{
if(Message!="Thread was being aborted.")
{
//in the web config specify the path(where to store log file like ()).
string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorFolder"] + "\\" + DateTime.Now.ToString("dd-MM-yyyy") + ".xml");


if (!File.Exists(path))
{
XmlTextWriter writer = new XmlTextWriter(path, Encoding.Unicode);
writer.WriteStartDocument(true);
writer.WriteStartElement("LOGGER");
writer.WriteEndElement();
writer.Close();
LogDoc = new XmlDocument();
LogDoc.Load(path);
}
LogNode = LogDoc.DocumentElement;
LogElement = LogDoc.CreateElement("ELOG");
Message = Message.Replace("&", "&");
Message = Message.Replace("<", "<");
Message = Message.Replace(">", ">");
LogElement.InnerXml = "" + severity.ToString() + "" + Message + "";
LogNode.AppendChild(LogElement);

LogDoc.Save(path);
}
}
catch
{
}

}

// Nested Types
public enum Severity
{
Error = 2,
Failure = 3,
Informational = 1
}
}

on the aspx/ascx in a catch block write below lines

2) AppLogger.LogError("User Edit Profile, Sending Mail() " + ex.Message, AppLogger.Severity.Error);

TXT format
1)Create .cs file

public static void ErrorLogFile(string strErrorMessage)
{
try
{
string strPath = "~/LogFile/ErrorDetails/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(strPath)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(strPath)).Close();
}
using (StreamWriter sWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(strPath)))
{
sWriter.WriteLine("\r\nLog Entry : ");
sWriter.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
string strError = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
". Error Message:" + strErrorMessage;
sWriter.WriteLine(strError);
sWriter.WriteLine("__________________________");
sWriter.Flush();
sWriter.Close();
}
}
catch (Exception ex)
{
ErrorLogFile(ex.Message);
}

}
2)call this file catch block
clsLogFile.ErrorLogFile(ex.Message);

The same way we can track the mail sent details from the server.

Optimization

# Try to restrict the queries result set by using the WHERE clause.
This can results in good performance benefits, because SQL Server will return to client only particular rows, not all rows from the table(s). This can reduce network traffic and boost the overall performance of the query.

# Try to restrict the queries result set by returning only the particular columns from the table, not all table's columns.
This can results in good performance benefits, because SQL Server will return to client only particular columns, not all table's columns. This can reduce network traffic and boost the overall performance of the query.

# Use views and stored procedures instead of heavy-duty queries.
This can reduce network traffic, because your client will send to server only stored procedure or view name (perhaps with some parameters) instead of large heavy-duty queries text. This can be used to facilitate permission management also, because you can restrict user access to table columns they should not see.


# Try to avoid using SQL Server cursors, whenever possible.
SQL Server cursors can result in some performance degradation in comparison with select statements. Try to use correlated subquery or derived tables, if you need to perform row-by-row operations.


# If you need to return the total table's row count, you can use alternative way instead of SELECT COUNT(*) statement.
Because SELECT COUNT(*) statement make a full table scan to return the total table's row count, it can take very many time for the large table. There is another way to determine the total row count in a table. You can use sysindexes system table, in this case. There is ROWS column in the sysindexes table. This column contains the total row count for each table in your database. So, you can use the following select statement instead of SELECT COUNT(*): SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2 So, you can improve the speed of such queries in several times.
See this article for more details:
Alternative way to get the table's row count.

# Try to use constraints instead of triggers, whenever possible.
Constraints are much more efficient than triggers and can boost performance. So, you should use constraints instead of triggers, whenever possible.


# Use table variables instead of temporary tables.
Table variables require less locking and logging resources than temporary tables, so table variables should be used whenever possible. The table variables are available in SQL Server 2000 only.


# Try to avoid the HAVING clause, whenever possible.
The HAVING clause is used to restrict the result set returned by the GROUP BY clause. When you use GROUP BY with the HAVING clause, the GROUP BY clause divides the rows into sets of grouped rows and aggregates their values, and then the HAVING clause eliminates undesired aggregated groups. In many cases, you can write your select statement so, that it will contain only WHERE and GROUP BY clauses without HAVING clause. This can improve the performance of your query.

# Try to avoid using the DISTINCT clause, whenever possible.
Because using the DISTINCT clause will result in some performance degradation, you should use this clause only when it is necessary.


# Include SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL statement.
This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a T-SQL statement.


# Use the select statements with TOP keyword or the SET ROWCOUNT statement, if you need to return only the first n rows.
This can improve performance of your queries, because the smaller result set will be returned. This can also reduce the traffic between the server and the clients.

# Use the FAST number_rows table hint if you need to quickly return 'number_rows' rows.
You can quickly get the n rows and can work with them, when the query continues execution and produces its full result set.


# Try to use UNION ALL statement instead of UNION, whenever possible.
The UNION ALL statement is much faster than UNION, because UNION ALL statement does not look for duplicate rows, and UNION statement does look for duplicate rows, whether or not they exist.

# Do not use optimizer hints in your queries.
Because SQL Server query optimizer is very clever, it is very unlikely that you can optimize your query by using optimizer hints, more often, this will hurt performance.

Localization

To specify the culture (language basis to load the text) follow the below steps:

Default Folder which it's get creat by vs.net

App_GlobalResources

1)Create a resource file (Contactus.resx) it is common for English. based on the langeuage needs to specify the culture text name like (Contactus.it.resx- for itally,Contactus.de.resx - for detuch)
how ever the label's specify
2)
void Loadtext()
{
lblfname.Text = Resources.Contactus.lblfname;
lblsurname.Text = Resources.Contactus.lblsname;
lblemail.Text = Resources.Contactus.lblemail;
lblGender.Text = Resources.Contactus.lblgender;
lblphone.Text = Resources.Contactus.lblphone;
}

3) Call the above method on your page load event. based on the culture it's read from the App_GlobalResources.

Copyright © 2009 Angel