MCTS is the acronym of Microsoft Certified Technology Specialist. Through this credential, it validates to prove the candidate's ability in implementing successfully, building on, troubleshooting as well as debugging of a Microsoft technology which includes Microsoft exchange server, windows operating system, Microsoft visual studio and Microsoft SQL server. MCTS certification also validates the skills on functionality and features of key technologies. Candidate's can show their knowledge in depth on a particular technology and also can certify for multiple MCTS certification to show the ability across various products/ technologies.
Job roles for MCTS certified candidates:
There are several jobs available to the candidate's who have successfully completed and hold the MCTS certification. The following are the major job roles for MCTS certified candidates and they are:
1) Web developers.
2) Windows developers.
3) Enterprise software developers etc.
MCTS certification examination:
The official domains for this certification exam are as follows:
1) Deploying of windows vista
2) Management of widows vista security
3) Management and maintenance of systems that run windows vista
4) Troubleshooting as well as configuration of networking
5) Maintaining and supporting to desktop applications.
MCTS certification helps in building up of a strong career. By obtaining this certification, candidate's can gain latest relevant skills which are required to the employers for getting better opportunities in connection with globalized community of several certified professionals. In addition, this certification also provides the candidate to access exclusive Microsoft benefits as well as resources that includes career building training and tools, MCP member websites and other important specializations which are required in the field of Information technology. So, all candidates who wanted to hold this certification will be exploring the benefits of this certification in order to attain a strong career.
There are varieties of certifications which help you to step in to Information technology field and build a strong career. Similarly, for MCTS certification, candidates have to take part in the current year examination. There is a fee for all exams and these exam fees are subject to change due to local taxes as well as exchange rate in the daily market.
Alina Michael is CCNA and CCNP and MCTS Certified professional and currently working as Senior Network Engineer in London. She has helped thousands of IT professionals to get MCTS Certified via MCTS certification practice exams with money back passing guarantee. You may like to visit Certification Preparation for complete details about all certifications training products and prices.
Sunday, January 31, 2010
How to Prepare For MCTS Certification
Professionals who want to get in-depth knowledge of Microsoft technologies and want to enhance their IT carrier should opt for Microsoft Certified Technology Specialist or MCTS certification. This certification will enhance your knowledge in a particular Microsoft technology like Windows Vista, SQL Server, Windows mobile etc. Getting certification will show the commitment towards your willingness to study more and also will expertise you in a specific area where you can get command over it. MCTS certification will provide the foundation for Microsoft certifications. MCTS candidates are capable of implementing, building, troubleshooting, and debugging a particular Microsoft technology. As an MCTS, you become part of the Microsoft Certified Professional community, with access to all related benefits, information, and activities and there is no need to earn extra title for Microsoft Certified Professional (MCP).
To earn the certificate you have to give exams. Before giving exam you have to decide in which technology you want to get certified. Choose the certification exam you would like to take. There is one functional exam, and then you build from that exam to get the various form of MCTS designation. Total 17 designations are offered by Microsoft which is a wide range. Some of the exams are combinations are combination which will allow you to get a base certification now and expand it later.
For a good preparation of MCTS certification, take an assessment quiz offered by Microsoft which will let you know where you stand in terms of technology do. If you are a self learner then Microsoft provides self guided books and practical exams considerably at less money which includes official self-paced study guide, practice tests with multiple, customizable testing options and a learning plan based on your results, 450 practice and review questions, case scenarios and lab exercises, code samples on CD, 90-day evaluation version of Microsoft Visual Studio 2005 Professional Edition, fully searchable eBook otherwise opt for training courses and attend the classes.
Main exam will be of maximum four hours. Candidate can go before that time if completed earlier. MCTS certifications will be valid till Microsoft continues mainstream support for related technology.
If you are looking for MCTS exams training like 70-236 and 70-542. I'd like to advise to make use of practice exams, study guides, selftest engines, certification tutorials developed by Industry leading Exams Expert with 100% passing and money back guarantee incase you fail in your exam. Visit for more details.
Saturday, January 30, 2010
XML Web Services Using ASP.NET
Building a simple Web service using ASP.NET is relatively easy and is covered in ASP.NET XML Web Service Basics and Walkthrough: Building a Basic XML Web Service Using ASP.NET. However, the true power of Web services is realized when you look at the infrastructure. Web services are built on top of the .NET Framework and the common language runtime. A Web service can take advantage of these technologies. For instance, the performance, state management, and authentication supported by ASP.NET can all be taken advantage of by building Web services using ASP.NET.
The infrastructure for Web services is built to conform to industry standards such as SOAP, XML, and WSDL, and this allows clients from other platforms to interoperate with Web services. As long as a client can send standards-compliant SOAP messages, formatted according to a service description, that client can call a Web service created using ASP.NET (regardless of the platform on which the client resides). For more information on how ASP.NET provides an attribute-based mechanism for modifying the format of the expected SOAP, see Customizing SOAP Message Formatting.
When you build a Web service using ASP.NET, it automatically supports clients communicating using the SOAP, HTTP-GET, and HTTP-POST protocols. Since HTTP-GET and HTTP-POST support passing messages in URL-encoded name-value pairs, the data type support for these two protocols is not as rich as that supported for SOAP. In SOAP, which passes data to and from the Web service using XML, you can define complex data types using XSD schemas, which support a richer set of data types. Developers building a Web service using ASP.NET do not have to explicitly define complex data types they expect using an XSD schema. Rather, they can simply build a managed class. ASP.NET handles mapping class definitions to an XSD schema and mapping object instances to XML data in order to pass it back and forth across a network.
The infrastructure for Web services is built to conform to industry standards such as SOAP, XML, and WSDL, and this allows clients from other platforms to interoperate with Web services. As long as a client can send standards-compliant SOAP messages, formatted according to a service description, that client can call a Web service created using ASP.NET (regardless of the platform on which the client resides). For more information on how ASP.NET provides an attribute-based mechanism for modifying the format of the expected SOAP, see Customizing SOAP Message Formatting.
When you build a Web service using ASP.NET, it automatically supports clients communicating using the SOAP, HTTP-GET, and HTTP-POST protocols. Since HTTP-GET and HTTP-POST support passing messages in URL-encoded name-value pairs, the data type support for these two protocols is not as rich as that supported for SOAP. In SOAP, which passes data to and from the Web service using XML, you can define complex data types using XSD schemas, which support a richer set of data types. Developers building a Web service using ASP.NET do not have to explicitly define complex data types they expect using an XSD schema. Rather, they can simply build a managed class. ASP.NET handles mapping class definitions to an XSD schema and mapping object instances to XML data in order to pass it back and forth across a network.
Introduction to Programming Web Services in Managed Code
Web services make possible the exchange of data in the form of XML messages between heterogeneous systems. Although remote access of data and application logic is not a new concept, doing so in a loosely coupled fashion is. Previous attempts, such as DCOM, IIOP, and Java/RMI, required tight integration between the client and the server and used platform and implementation specific binary data formats. While such protocols require a particular component technology or object-calling convention, Web services do not. The only assumption made between the client and the server is that recipients will understand the messages they receive. In other words, the client and server agree to a contract, in this case described using WSDL and XSD, and then communicate by generating messages that honor the contract over a specified transport like HTTP. As a result, programs written in any language, using any component model, and running on any operating system can access Web services. Furthermore, the flexibility of using a text format like XML makes possible the message exchange to evolve over time in a loosely coupled way. This loose coupling is mandatory in environments where the simultaneous updating of all parties in the message exchange is not possible.
You create Web services using the ASP.NET page framework, enabling these Web services to access the many features of the .NET Framework, such as authentication, caching, and state management. Because ASP.NET and the .NET Framework are the basis for Web services in managed code, developers can focus on creating or accessing Web services without needing to write infrastructure code.
In the ASP.NET application model, Web pages intended for the browser use the .aspx extension. To differentiate Web services from regular ASP.NET pages, Web services use the .asmx extension.
There are two fundamental roles when working with Web services:
Creating a Web service — When you create an XML Web service, you are creating an application that exposes functionality to XML Web service clients.
Accessing a Web service — When you access a Web service, your client application locates, references, and uses the functionality contained within a separate Web service. The client of an XML Web service is typically an application that is able to send, receive, and process messages to and from the Web service. However, the minimum requirement is that the client must be able to send messages to the Web service. This includes all applications using the .NET Framework.
Web services can be either stand-alone applications or sub-components of a larger Web application. For example, suppose you are creating a Web application that sells books online. Your Web application might interact with Web services as follows:
Creating Web service — Your application exposes its order processing logic as a Web service, which your affiliate Web sites can in turn use in their Web applications to sell books through your online store without requiring their customers to visit your site.
Accessing Web service — Your application accesses Web service provided by another online company that specializes in writing and supplying book reviews for online booksellers. When a visitor to your online store views the details of a particular book, they also see the reviews of that book on the same page.
You create Web services using the ASP.NET page framework, enabling these Web services to access the many features of the .NET Framework, such as authentication, caching, and state management. Because ASP.NET and the .NET Framework are the basis for Web services in managed code, developers can focus on creating or accessing Web services without needing to write infrastructure code.
In the ASP.NET application model, Web pages intended for the browser use the .aspx extension. To differentiate Web services from regular ASP.NET pages, Web services use the .asmx extension.
There are two fundamental roles when working with Web services:
Creating a Web service — When you create an XML Web service, you are creating an application that exposes functionality to XML Web service clients.
Accessing a Web service — When you access a Web service, your client application locates, references, and uses the functionality contained within a separate Web service. The client of an XML Web service is typically an application that is able to send, receive, and process messages to and from the Web service. However, the minimum requirement is that the client must be able to send messages to the Web service. This includes all applications using the .NET Framework.
Web services can be either stand-alone applications or sub-components of a larger Web application. For example, suppose you are creating a Web application that sells books online. Your Web application might interact with Web services as follows:
Creating Web service — Your application exposes its order processing logic as a Web service, which your affiliate Web sites can in turn use in their Web applications to sell books through your online store without requiring their customers to visit your site.
Accessing Web service — Your application accesses Web service provided by another online company that specializes in writing and supplying book reviews for online booksellers. When a visitor to your online store views the details of a particular book, they also see the reviews of that book on the same page.
Web Services:
Web services are components on a Web server that a client application can call by making HTTP requests across the Web. ASP.NET enables you to create custom Web services or to use built-in application services, and to call these services from any client application.
Friday, January 29, 2010
WPF ListView which can do - sorting, filtering, totals, cell-focus, editing, and more...............
Introduction
It was one of those days. In a solution, the bottleneck was figured out. Once again, it was the third party DataGrid I used. After having tried three different vendors, I was frustrated, and went back to the ListView, and the performance was back to slow. I wanted the DataGrid to present the data fast, specially when I reset the ItemsSource to a new collection.
Without a doubt, the commercial DataGrids are nice looking and feature rich. But the overhead on all that slows them down. The DataGrid from Microsoft never could win my interest, it seems somewhere in between the ListView and the commercial DataGrids. Anyways, I started to tweak the ListView, and here is what I've managed to do.
The basic usage should be easier
Some thing always annoyed me when using commercial DataGrids or the ListView itself. I was tired of writing all those CellTemplates I would have to use. WPF has its own paradigm, but a DataGrid is a DataGrid, at least most of the time.
Wanted Features
Common configuration scenarios available through properties
Default style for the whole grid and optional styles for columns
Lightweight styling and customizing without re-templating
Sorting any column, and SortName property for first-run
Filtering any column (AutoFilter row)
Totals/Summaries for any column
Frozen column left/right
GridLines vertical and horizontal
Cell-focus (cursor)
Cell-editing
Using the code
The basic usage of the DsxDataGrid is pretty straightforward. You can think of it as a 'ListView'. It is a custom control derived from Selector. The ControlTemplates are mainly based on the ListView. The following snippet shows most of the properties for the additional features:
Margin="5"
AllowCheckAnyTime="True"
SortField="CompanyName"
HorizontalGridLinesIsVisible="True"
VerticalGridLinesIsVisible="True"
CellAdornerIsVisible="True"
CellEditingIsEnabled="True"
HeaderVisibility="Visible"
FilterVisibility="Auto"
FooterVisibility="Auto"
ItemFixHeight="20"
AreaLeftWidth="212"
AreaRightWidth="250"
SplitterLeftWidth="3"
SplitterLeftIsSizing="False"
SplitterRightWidth="3"
SplitterRightIsSizing="False"
IsVirtualizing="False">
IsSizable="False" IsSortable="False"
ViewType="CheckBox" FilterType="CheckBox"
FooterType="None" EditType="None"
CellHAlign="Center"/>
IsSizable="False" ViewType="Text"
FilterType="TextBox" FooterType="Count"
EditType="TextBox" CellHAlign="Left"
CellForeground="Blue"
CellBackground="#33C3E8D1"/>
ViewType="Text" FilterType="ComboBox"
FooterType="None" EditType="ComboBox"
CellHAlign="Left"
CellContentItemsSource="{x:Static local:ContactTitles.ComboSource}"/>
Most basic columns are ready to use without CellTemplates. Behind the scenes, the CellTemplates are generated.
The basic layout of DsxDataGrid
The DataGrid is divided in three areas. Each area contains a ListView with the same style. The right area is configured to show the vertical scrollbar, and contains the additional areas that fill the special rows. The header (blue), filter (green), and footer (purple) are all GridViewHeaderRowPresenters but with different Styles (ControlTemplates). The synchronization of the vertical scrolling is done by the very useful ScrollSynchronizer: Scroll Synchronization by Karin Huber
Important: if the left and center areas are not needed, only the area on the right is shown.
Column ViewTypes
Each column has a ViewType (default is Text). This injects a CellTemplate to be created that does everything needed.
Collapse Copy Code
public enum EViewType
{
Text = 1,
Integer = 2,
Decimal = 3,
Currency = 4,
Date = 5,
Boolean = 6, // displays BulletChrome
CheckBox = 7,
Image = 8,
Progress = 9,
}In order to serve the different ListView areas, the columns are recreated inside the contained ListView Columns collections. In this step, the column is examined, and depending on the settings, the CellTemplates are generated for the different ViewTypes. In this scenario, I prefer code over XAML, because in code, you can do nasty things like reuse the existing DisplayMemberBinding, and you have full control to minimize the CellTemplates to a minimum.
Column FilterTypes / EditTypes
Each column can have a FilterType and or an EditType, both of type EEditType. If a FilterType is set, the FilterRow displays the FilterCell. The editing is done by placing an Adorner over the current cell. All controls used in the Adorner are configured to look nice even if the cell is of variable height. This approach is much lighter than placing full controls inside column-cells.
Collapse Copy Code
public enum EEditType
{
None = 0,
TextBox = 1,
CheckBox = 2,
DatePicker = 3,
ComboBox = 4,
Slider = 5,
CellTemplate = 6, // not valid for Filter
}Note: All EditTypes are templated to look nice if the ItemHeight is larger than the EditControl usually is:
Column FooterTypes
A FooterType can be set on a column to display a result on the displayed data. If the displayed data is filtered, the result is narrowed to the filtered data.
Collapse Copy Code
public enum EFooterType
{
None = 0,
Sum = 1,
Avg = 2,
Min = 3,
Max = 4,
Count = 5,
}How Sorting/Filtering/Summarize work
Sorting can be invoked either by setting the SortField property on the DataGrid, or by clicking the column-header. Both check first if the referring column allows sorting. The sorting triggers the DisplaySource (result of displayed data) to be re-evaluated. In there, the ICollectionView will do the sorting.
Filtering is invoked by the Adorner and is not accessible by property. The filtering acts on PropertyChanged, but has a short timer to wait for some time before invoking the routine. The filtering triggers the DisplaySource to be re-evaluated too. A callback handles all filter-columns to be checked.
Summarizing the totals is (like you might guess) also done while rebuilding the DisplaySource. Since there is no way to build a sum without enumerating all relevant items at least once, this is done by a simple loop before presenting the data.
Custom CellTemplates
In the sample, the column 'Address' uses a custom CellTemplate, triggering the EditMode property that takes control over the editing (entering/exiting). It would probably easier to enhance the existing types in code, so one could as well use a CellTemplate.
How to Define Alternating RowColors
AlternationCount/-Index is already prepared in the ItemsControl. DsxDataGrid just has the collection for the brushes all ready for use, so you just do this, and it will work:
Collapse Copy Code
My approach is to have a default style for header/filter/footer on the DataGrid that is used for every column, but some columns override the style. The GridViewHeaderRowPresenter gets the style from the custom Control-Template, which refers (if not replaced) to, e.g., the dsxFilterStyle (for FilterRow). In this style, you can see this:
Collapse Copy Code
All used properties to style the filters refer to a converter. The converter itself evaluates if there is a style on the column overriding the style on the DataGrid, or maybe none at all.
More Details, Sorry so much!
Unfortunately, I cannot explain all the little tweaks I built in, there are many, and my time is not sufficient for that. Some solutions maybe no rocket science, but they do the job. And yes, I suppose some could be done much more elegantly. But for now, I hope there is some usage for those who come along here because they need ideas.
Limitations
DsxDataGrid must use ItemFixHeight if IsVirtualizing is set or there are multiple areas (frozen column on left and/or right side).
The filters do not listen to changes in the filtered fields of the underlying source.
What is Missing/Needs Redesign?
Grouping, best if IsVirtualizing could be kept (flattened GroupCollections)
Make the filter listen to changes
Redesign frozen columns (WPFToolKit DataGrid has an implementation)
What I have Learned?
Having different areas or frozen columns organized in different independent ListViews is not the best practice. I rarely use that so I can go with the current solution for now. If I knew from the start, I would have invested my time in writing my own GridViewRowPresenter. But I did not want to go down that deep when I started. Well, like the saying: all people are smart - some before, some after
File Download Using JavaScript
Introduction
I know there are many developers looking for this kind of solution like I was looking. I had the same requirement to download the file from the server using JavaScript and with out postbacking the full page. The beauty of this is, it will work in IE/Firefox/Chrome browsers. I have not used ScriptManager/UpdatePanel anything rather I used Handler and normal JavaScript code. Handler is used to write the response back to the page. I have noted down the steps you may use in your programming. I can not use ActiveXObject in Firefox to create excel object in JavaScript because ActiveXObject will not work in Firefox.
How Did I Do This?
Add span tag on the page which will work as a link
Create FileHandler.ashx to write the response back to the page. Collapse Copy Code
public void ProcessRequest(HttpContext context)
{
fileName = HttpUtility.UrlDecode(context.Request.Params["fileName"]);
string FullFilePath = context.Server.MapPath("~/Common/Files/" + fileName);
FileInfo file = new FileInfo(FullFilePath);
if (file.Exists)
{
context.Response.ContentType =
MIMETypeUtility.MIMETypeDescription(MIMEType.Excel);
context.Response.AddHeader
("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
context.Response.AddHeader("Content-Length", file.Length.ToString());
context.Response.WriteFile(file.FullName);
context.Response.End();
}
} You can use any MIME Type according to your requirement. I have showed some of the MIME types you can use in your application. For more MIME types, list http://msdn.microsoft.com/en-us/library/ms775147%28VS.85%29.aspx
public enum MIMEType
{
[DescriptionAttribute("text/HTML")]TextHTML,
[DescriptionAttribute("image/GIF")]Gif,
[DescriptionAttribute("image/JPEG")]JPEG,
[DescriptionAttribute("text/plain")]TextPlain,
[DescriptionAttribute("Application/msword")]Word,
[DescriptionAttribute("Application/vnd.ms-excel")]Excel,
[DescriptionAttribute("Application/vnd.xls")]FirefoxExcel
}
public class MIMETypeUtility
{
public static string MIMETypeDescription(Enum mimeType)
{
FieldInfo fi = mimeType.GetType().GetField(mimeType.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes
(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return mimeType.ToString();
}
}
} Create FileHandler.js file to do the main work. It will create an iframe dynamically and which has width, height and border as 0. Then create form tag with one input control to pass filename (e.g. ExcelFile.xls) when you submit an iframe.
var createFrame = function()
{
var frame = document.createElement("iframe");
frame.name = "fileFrame";
frame.id = "fileFrame";
document.body.appendChild(frame);
generateIFrameContent();
frame.style.width = "0px";
frame.style.height = "0px";
frame.style.border = "0px";
}GetExcelFile function will pass Excel file name as parameter and will submit an iframe window and handler will run the code and writes the file response back to the page and the user will get open/save/cancel dialog window. Collapse Copy Code
var getExcelFile = function()
{
var frmWindow = getIFrameWindow();
var fileName = frmWindow.document.getElementById("fileName");
fileName.value = encodeURI("ExcelFile.xls");
var frm = frmWindow.document.getElementById("frmFile");
frm.submit();
} Create LoadScript.aspx page to add scripts to the page response. Here you can add any number of scripts and I prefer this way where I can hide the JavaScript and the location of the script file in page source at runtime. Collapse Copy Code
private void loadScript()
{
List scripts = new List();
scripts.Add(Server.MapPath("~/Common/JS/FileHandler.js"));
try
{
bool isStyles = this.GetType().BaseType.Name == "Styles";
this.Response.Clear();
this.Response.ContentType = isStyles ? "text/css" : "text/javascript";
byte[] data = null;
try
{
StringBuilder sb = new StringBuilder();
foreach (string str in scripts)
sb.Append(File.ReadAllText(str));
data = new ASCIIEncoding().GetBytes(sb.ToString());
}
catch (Exception ex)
{
throw ex;
}
this.Response.AddHeader("Content-Length", data.LongLength.ToString());
this.Response.BinaryWrite(data);
this.Response.End();
}
catch (Exception ex)
{
throw ex;
}
} Add the following code to the FileHandler.aspx page to load scripts and startupscript with initialization of JavaScript function. Collapse Copy Code
protected void Page_Load(object sender, EventArgs e)
{
Type type = this.GetType();
if (!this.ClientScript.IsClientScriptIncludeRegistered(type, "scrScripts"))
this.ClientScript.RegisterClientScriptInclude
(type, "scrScripts", "Common/Loaders/LoadScripts.aspx");
if (!this.ClientScript.IsStartupScriptRegistered(type, "scrHandlerStartUp"))
this.ClientScript.RegisterStartupScript
(type, "scrHandlerStartUp", GetStartUpScript(), true);
}
private string GetStartUpScript()
{
return "try{{var handler = new FileHandler();handler.init();}}catch(e)
{{document.getElementById('divNotLoaded').style.display = '';}}";
}
ConclusionYou can use AJAX (Scriptmanager + Updatepanel) to download the file from server, but you have to post back the page. This technique is light weight on the page. I had the requirement in my project to get the data from database and create an Excel file and insert the data and download the file to user machine. And my total website is using AJAX (JS+WebServices and no updatepanel), in this case I cannot use any server controls because that will post back my full page and I do not want that to happen. So after much R&D and many ways, this is one technique I have come up to use and it's working successfully in the production.
I know there are many developers looking for this kind of solution like I was looking. I had the same requirement to download the file from the server using JavaScript and with out postbacking the full page. The beauty of this is, it will work in IE/Firefox/Chrome browsers. I have not used ScriptManager/UpdatePanel anything rather I used Handler and normal JavaScript code. Handler is used to write the response back to the page. I have noted down the steps you may use in your programming. I can not use ActiveXObject in Firefox to create excel object in JavaScript because ActiveXObject will not work in Firefox.
How Did I Do This?
Add span tag on the page which will work as a link
Create FileHandler.ashx to write the response back to the page. Collapse Copy Code
public void ProcessRequest(HttpContext context)
{
fileName = HttpUtility.UrlDecode(context.Request.Params["fileName"]);
string FullFilePath = context.Server.MapPath("~/Common/Files/" + fileName);
FileInfo file = new FileInfo(FullFilePath);
if (file.Exists)
{
context.Response.ContentType =
MIMETypeUtility.MIMETypeDescription(MIMEType.Excel);
context.Response.AddHeader
("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
context.Response.AddHeader("Content-Length", file.Length.ToString());
context.Response.WriteFile(file.FullName);
context.Response.End();
}
} You can use any MIME Type according to your requirement. I have showed some of the MIME types you can use in your application. For more MIME types, list http://msdn.microsoft.com/en-us/library/ms775147%28VS.85%29.aspx
public enum MIMEType
{
[DescriptionAttribute("text/HTML")]TextHTML,
[DescriptionAttribute("image/GIF")]Gif,
[DescriptionAttribute("image/JPEG")]JPEG,
[DescriptionAttribute("text/plain")]TextPlain,
[DescriptionAttribute("Application/msword")]Word,
[DescriptionAttribute("Application/vnd.ms-excel")]Excel,
[DescriptionAttribute("Application/vnd.xls")]FirefoxExcel
}
public class MIMETypeUtility
{
public static string MIMETypeDescription(Enum mimeType)
{
FieldInfo fi = mimeType.GetType().GetField(mimeType.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes
(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return mimeType.ToString();
}
}
} Create FileHandler.js file to do the main work. It will create an iframe dynamically and which has width, height and border as 0. Then create form tag with one input control to pass filename (e.g. ExcelFile.xls) when you submit an iframe.
var createFrame = function()
{
var frame = document.createElement("iframe");
frame.name = "fileFrame";
frame.id = "fileFrame";
document.body.appendChild(frame);
generateIFrameContent();
frame.style.width = "0px";
frame.style.height = "0px";
frame.style.border = "0px";
}GetExcelFile function will pass Excel file name as parameter and will submit an iframe window and handler will run the code and writes the file response back to the page and the user will get open/save/cancel dialog window. Collapse Copy Code
var getExcelFile = function()
{
var frmWindow = getIFrameWindow();
var fileName = frmWindow.document.getElementById("fileName");
fileName.value = encodeURI("ExcelFile.xls");
var frm = frmWindow.document.getElementById("frmFile");
frm.submit();
} Create LoadScript.aspx page to add scripts to the page response. Here you can add any number of scripts and I prefer this way where I can hide the JavaScript and the location of the script file in page source at runtime. Collapse Copy Code
private void loadScript()
{
List
scripts.Add(Server.MapPath("~/Common/JS/FileHandler.js"));
try
{
bool isStyles = this.GetType().BaseType.Name == "Styles";
this.Response.Clear();
this.Response.ContentType = isStyles ? "text/css" : "text/javascript";
byte[] data = null;
try
{
StringBuilder sb = new StringBuilder();
foreach (string str in scripts)
sb.Append(File.ReadAllText(str));
data = new ASCIIEncoding().GetBytes(sb.ToString());
}
catch (Exception ex)
{
throw ex;
}
this.Response.AddHeader("Content-Length", data.LongLength.ToString());
this.Response.BinaryWrite(data);
this.Response.End();
}
catch (Exception ex)
{
throw ex;
}
} Add the following code to the FileHandler.aspx page to load scripts and startupscript with initialization of JavaScript function. Collapse Copy Code
protected void Page_Load(object sender, EventArgs e)
{
Type type = this.GetType();
if (!this.ClientScript.IsClientScriptIncludeRegistered(type, "scrScripts"))
this.ClientScript.RegisterClientScriptInclude
(type, "scrScripts", "Common/Loaders/LoadScripts.aspx");
if (!this.ClientScript.IsStartupScriptRegistered(type, "scrHandlerStartUp"))
this.ClientScript.RegisterStartupScript
(type, "scrHandlerStartUp", GetStartUpScript(), true);
}
private string GetStartUpScript()
{
return "try{{var handler = new FileHandler();handler.init();}}catch(e)
{{document.getElementById('divNotLoaded').style.display = '';}}";
}
ConclusionYou can use AJAX (Scriptmanager + Updatepanel) to download the file from server, but you have to post back the page. This technique is light weight on the page. I had the requirement in my project to get the data from database and create an Excel file and insert the data and download the file to user machine. And my total website is using AJAX (JS+WebServices and no updatepanel), in this case I cannot use any server controls because that will post back my full page and I do not want that to happen. So after much R&D and many ways, this is one technique I have come up to use and it's working successfully in the production.
Subscribe to:
Posts (Atom)