function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) { this.eventTarget = eventTarget; this.eventArgument = eventArgument; this.validation = validation; this.validationGroup = validationGroup; this.actionUrl = actionUrl; this.trackFocus = trackFocus; this.clientSubmit = clientSubmit; } function WebForm_DoPostBackWithOptions(options) { var validationResult = true; if (options.validation) { if (typeof (Page_ClientValidate) == 'function') { validationResult = Page_ClientValidate(options.validationGroup); } } if (validationResult) { if ((typeof (options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) { theForm.action = options.actionUrl; } if (options.trackFocus) { var lastFocus = theForm.elements["__LASTFOCUS"]; if ((typeof (lastFocus) != "undefined") && (lastFocus != null)) { if (typeof (document.activeElement) == "undefined") { lastFocus.value = options.eventTarget; } else { var active = document.activeElement; if ((typeof (active) != "undefined") && (active != null)) { if ((typeof (active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) { lastFocus.value = active.id; } else if (typeof (active.name) != "undefined") { lastFocus.value = active.name; } } } } } } if (options.clientSubmit) { __doPostBack(options.eventTarget, options.eventArgument); } } var __pendingCallbacks = new Array(); var __synchronousCallBackIndex = -1; function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) { var postData = __theFormPostData + "__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) + "&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument); if (theForm["__EVENTVALIDATION"]) { postData += "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value); } var xmlRequest, e; try { xmlRequest = new XMLHttpRequest(); } catch (e) { try { xmlRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } var setRequestHeaderMethodExists = true; try { setRequestHeaderMethodExists = (xmlRequest && xmlRequest.setRequestHeader); } catch (e) { } var callback = new Object(); callback.eventCallback = eventCallback; callback.context = context; callback.errorCallback = errorCallback; callback.async = useAsync; var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback); if (!useAsync) { if (__synchronousCallBackIndex != -1) { __pendingCallbacks[__synchronousCallBackIndex] = null; } __synchronousCallBackIndex = callbackIndex; } if (setRequestHeaderMethodExists) { xmlRequest.onreadystatechange = WebForm_CallbackComplete; callback.xmlRequest = xmlRequest; xmlRequest.open("POST", theForm.action, true); xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); xmlRequest.send(postData); return; } callback.xmlRequest = new Object(); var callbackFrameID = "__CALLBACKFRAME" + callbackIndex; var xmlRequestFrame = document.frames[callbackFrameID]; if (!xmlRequestFrame) { xmlRequestFrame = document.createElement("IFRAME"); xmlRequestFrame.width = "1"; xmlRequestFrame.height = "1"; xmlRequestFrame.frameBorder = "0"; xmlRequestFrame.id = callbackFrameID; xmlRequestFrame.name = callbackFrameID; xmlRequestFrame.style.position = "absolute"; xmlRequestFrame.style.top = "-100px" xmlRequestFrame.style.left = "-100px"; try { if (callBackFrameUrl) { xmlRequestFrame.src = callBackFrameUrl; } } catch (e) { } document.body.appendChild(xmlRequestFrame); } var interval = window.setInterval(function () { xmlRequestFrame = document.frames[callbackFrameID]; if (xmlRequestFrame && xmlRequestFrame.document) { window.clearInterval(interval); xmlRequestFrame.document.write(""); xmlRequestFrame.document.close(); xmlRequestFrame.document.write('<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>'); xmlRequestFrame.document.close(); xmlRequestFrame.document.forms[0].action = theForm.action; var count = __theFormPostCollection.length; var element; for (var i = 0; i < count; i++) { element = __theFormPostCollection[i]; if (element) { var fieldElement = xmlRequestFrame.document.createElement("INPUT"); fieldElement.type = "hidden"; fieldElement.name = element.name; fieldElement.value = element.value; xmlRequestFrame.document.forms[0].appendChild(fieldElement); } } var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT"); callbackIdFieldElement.type = "hidden"; callbackIdFieldElement.name = "__CALLBACKID"; callbackIdFieldElement.value = eventTarget; xmlRequestFrame.document.forms[0].appendChild(callbackIdFieldElement); var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT"); callbackParamFieldElement.type = "hidden"; callbackParamFieldElement.name = "__CALLBACKPARAM"; callbackParamFieldElement.value = eventArgument; xmlRequestFrame.document.forms[0].appendChild(callbackParamFieldElement); if (theForm["__EVENTVALIDATION"]) { var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT"); callbackValidationFieldElement.type = "hidden"; callbackValidationFieldElement.name = "__EVENTVALIDATION"; callbackValidationFieldElement.value = theForm["__EVENTVALIDATION"].value; xmlRequestFrame.document.forms[0].appendChild(callbackValidationFieldElement); } var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT"); callbackIndexFieldElement.type = "hidden"; callbackIndexFieldElement.name = "__CALLBACKINDEX"; callbackIndexFieldElement.value = callbackIndex; xmlRequestFrame.document.forms[0].appendChild(callbackIndexFieldElement); xmlRequestFrame.document.forms[0].submit(); } }, 10); } function WebForm_CallbackComplete() { for (var i = 0; i < __pendingCallbacks.length; i++) { callbackObject = __pendingCallbacks[i]; if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) { if (!__pendingCallbacks[i].async) { __synchronousCallBackIndex = -1; } __pendingCallbacks[i] = null; var callbackFrameID = "__CALLBACKFRAME" + i; var xmlRequestFrame = document.getElementById(callbackFrameID); if (xmlRequestFrame) { xmlRequestFrame.parentNode.removeChild(xmlRequestFrame); } WebForm_ExecuteCallback(callbackObject); } } } function WebForm_ExecuteCallback(callbackObject) { var response = callbackObject.xmlRequest.responseText; if (response.charAt(0) == "s") { if ((typeof (callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) { callbackObject.eventCallback(response.substring(1), callbackObject.context); } } else if (response.charAt(0) == "e") { if ((typeof (callbackObject.errorCallback) != "undefined") && (callbackObject.errorCallback != null)) { callbackObject.errorCallback(response.substring(1), callbackObject.context); } } else { var separatorIndex = response.indexOf("|"); if (separatorIndex != -1) { var validationFieldLength = parseInt(response.substring(0, separatorIndex)); if (!isNaN(validationFieldLength)) { var validationField = response.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1); if (validationField != "") { var validationFieldElement = theForm["__EVENTVALIDATION"]; if (!validationFieldElement) { validationFieldElement = document.createElement("INPUT"); validationFieldElement.type = "hidden"; validationFieldElement.name = "__EVENTVALIDATION"; theForm.appendChild(validationFieldElement); } validationFieldElement.value = validationField; } if ((typeof (callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) { callbackObject.eventCallback(response.substring(separatorIndex + validationFieldLength + 1), callbackObject.context); } } } } } function WebForm_FillFirstAvailableSlot(array, element) { var i; for (i = 0; i < array.length; i++) { if (!array[i]) break; } array[i] = element; return i; } var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1); var __theFormPostData = ""; var __theFormPostCollection = new Array(); function WebForm_InitCallback() { var count = theForm.elements.length; var element; for (var i = 0; i < count; i++) { element = theForm.elements[i]; var tagName = element.tagName.toLowerCase(); if (tagName == "input") { var type = element.type; if ((type == "text" || type == "hidden" || type == "password" || ((type == "checkbox" || type == "radio") && element.checked)) && (element.id != "__EVENTVALIDATION")) { WebForm_InitCallbackAddField(element.name, element.value); } } else if (tagName == "select") { var selectCount = element.options.length; for (var j = 0; j < selectCount; j++) { var selectChild = element.options[j]; if (selectChild.selected == true) { WebForm_InitCallbackAddField(element.name, element.value); } } } else if (tagName == "textarea") { WebForm_InitCallbackAddField(element.name, element.value); } } } function WebForm_InitCallbackAddField(name, value) { var nameValue = new Object(); nameValue.name = name; nameValue.value = value; __theFormPostCollection[__theFormPostCollection.length] = nameValue; __theFormPostData += WebForm_EncodeCallback(name) + "=" + WebForm_EncodeCallback(value) + "&"; } function WebForm_EncodeCallback(parameter) { if (encodeURIComponent) { return encodeURIComponent(parameter); } else { return escape(parameter); } } var __disabledControlArray = new Array(); function WebForm_ReEnableControls() { if (typeof (__enabledControlArray) == 'undefined') { return false; } var disabledIndex = 0; for (var i = 0; i < __enabledControlArray.length; i++) { var c; if (__nonMSDOMBrowser) { c = document.getElementById(__enabledControlArray[i]); } else { c = document.all[__enabledControlArray[i]]; } if ((typeof (c) != "undefined") && (c != null) && (c.disabled == true)) { c.disabled = false; __disabledControlArray[disabledIndex++] = c; } } setTimeout("WebForm_ReDisableControls()", 0); return true; } function WebForm_ReDisableControls() { for (var i = 0; i < __disabledControlArray.length; i++) { __disabledControlArray[i].disabled = true; } } function WebForm_FireDefaultButton(event, target) { if (event.keyCode == 13) { var src = event.srcElement || event.target; if (!src || (src.tagName.toLowerCase() != "textarea")) { var defaultButton; if (__nonMSDOMBrowser) { defaultButton = document.getElementById(target); } else { defaultButton = document.all[target]; } if (defaultButton && typeof (defaultButton.click) != "undefined") { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } } } return true; } function WebForm_GetScrollX() { if (__nonMSDOMBrowser) { return window.pageXOffset; } else { if (document.documentElement && document.documentElement.scrollLeft) { return document.documentElement.scrollLeft; } else if (document.body) { return document.body.scrollLeft; } } return 0; } function WebForm_GetScrollY() { if (__nonMSDOMBrowser) { return window.pageYOffset; } else { if (document.documentElement && document.documentElement.scrollTop) { return document.documentElement.scrollTop; } else if (document.body) { return document.body.scrollTop; } } return 0; } function WebForm_SaveScrollPositionSubmit() { if (__nonMSDOMBrowser) { theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset; theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset; } else { theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX(); theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY(); } if ((typeof (this.oldSubmit) != "undefined") && (this.oldSubmit != null)) { return this.oldSubmit(); } return true; } function WebForm_SaveScrollPositionOnSubmit() { theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX(); theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY(); if ((typeof (this.oldOnSubmit) != "undefined") && (this.oldOnSubmit != null)) { return this.oldOnSubmit(); } return true; } function WebForm_RestoreScrollPosition() { if (__nonMSDOMBrowser) { window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value); } else { window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value); } if ((typeof (theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) { return theForm.oldOnLoad(); } return true; } function WebForm_TextBoxKeyHandler(event) { if (event.keyCode == 13) { var target; if (__nonMSDOMBrowser) { target = event.target; } else { target = event.srcElement; } if ((typeof (target) != "undefined") && (target != null)) { if (typeof (target.onchange) != "undefined") { target.onchange(); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } } } return true; } function WebForm_TrimString(value) { return value.replace(/^\s+|\s+$/g, '') } function WebForm_AppendToClassName(element, className) { var currentClassName = ' ' + WebForm_TrimString(element.className) + ' '; className = WebForm_TrimString(className); var index = currentClassName.indexOf(' ' + className + ' '); if (index === -1) { element.className = (element.className === '') ? className : element.className + ' ' + className; } } function WebForm_RemoveClassName(element, className) { var currentClassName = ' ' + WebForm_TrimString(element.className) + ' '; className = WebForm_TrimString(className); var index = currentClassName.indexOf(' ' + className + ' '); if (index >= 0) { element.className = WebForm_TrimString(currentClassName.substring(0, index) + ' ' + currentClassName.substring(index + className.length + 1, currentClassName.length)); } } function WebForm_GetElementById(elementId) { if (document.getElementById) { return document.getElementById(elementId); } else if (document.all) { return document.all[elementId]; } else return null; } function WebForm_GetElementByTagName(element, tagName) { var elements = WebForm_GetElementsByTagName(element, tagName); if (elements && elements.length > 0) { return elements[0]; } else return null; } function WebForm_GetElementsByTagName(element, tagName) { if (element && tagName) { if (element.getElementsByTagName) { return element.getElementsByTagName(tagName); } if (element.all && element.all.tags) { return element.all.tags(tagName); } } return null; } function WebForm_GetElementDir(element) { if (element) { if (element.dir) { return element.dir; } return WebForm_GetElementDir(element.parentNode); } return "ltr"; } function WebForm_GetElementPosition(element) { var result = new Object(); result.x = 0; result.y = 0; result.width = 0; result.height = 0; if (element.offsetParent) { result.x = element.offsetLeft; result.y = element.offsetTop; var parent = element.offsetParent; while (parent) { result.x += parent.offsetLeft; result.y += parent.offsetTop; var parentTagName = parent.tagName.toLowerCase(); if (parentTagName != "table" && parentTagName != "body" && parentTagName != "html" && parentTagName != "div" && parent.clientTop && parent.clientLeft) { result.x += parent.clientLeft; result.y += parent.clientTop; } parent = parent.offsetParent; } } else if (element.left && element.top) { result.x = element.left; result.y = element.top; } else { if (element.x) { result.x = element.x; } if (element.y) { result.y = element.y; } } if (element.offsetWidth && element.offsetHeight) { result.width = element.offsetWidth; result.height = element.offsetHeight; } else if (element.style && element.style.pixelWidth && element.style.pixelHeight) { result.width = element.style.pixelWidth; result.height = element.style.pixelHeight; } return result; } function WebForm_GetParentByTagName(element, tagName) { var parent = element.parentNode; var upperTagName = tagName.toUpperCase(); while (parent && (parent.tagName.toUpperCase() != upperTagName)) { parent = parent.parentNode ? parent.parentNode : parent.parentElement; } return parent; } function WebForm_SetElementHeight(element, height) { if (element && element.style) { element.style.height = height + "px"; } } function WebForm_SetElementWidth(element, width) { if (element && element.style) { element.style.width = width + "px"; } } function WebForm_SetElementX(element, x) { if (element && element.style) { element.style.left = x + "px"; } } function WebForm_SetElementY(element, y) { if (element && element.style) { element.style.top = y + "px"; } }
Thursday, September 16, 2010
Asp.net Postback and Utility script
Wednesday, September 15, 2010
How to take a snapshot of the a current aspx page using WebBrowser
The idea is to use System.Windows.Forms.WebBrowser control and get a snapshot of the working page. I have developed a class called Thumbnail which we can use to create a snapshot providing a URL or html text. I use html text mode in there. I provide html text plus the method as html. In the constructor it initializes the object.
Putting all together
Markup:
Code:
Thumbnail thumbnail = new Thumbnail(html, 800, 600, width, height, Thumbnail.ThumbnailMethod.Html);Then the GenerateThumbnail method is the most important bit. However in-order to use WebBrowser control in a web page (MTA – Multi Threaded Apartment) we have to execute the WebBrowser control in a STA (Single Thread Apartment). For this I create a separate thread a set apartment state to STA.
public Bitmap GenerateThumbnail() { Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); return ThumbnailImage; }In the thread start, as the internal method I use GenerateThumbnailInternal method. In that method, I assign an event handler to the web browser object’s DocumentCompleted method. But the problem is it takes a while to web browser complete the request. By that time page finishes the execution. So we have to delay the page execution until WebBrowser completes the request. For this I use Application.DoEvents() method. I put the execution in a loop while WebBrowser is not completed its navigation.
private void GenerateThumbnailInteral() { WebBrowser webBrowser = new WebBrowser(); webBrowser.ScrollBarsEnabled = false; if (this.Method == ThumbnailMethod.Url) webBrowser.Navigate(this.Url); else webBrowser.DocumentText = this.Html; webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted); while (webBrowser.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents(); webBrowser.Dispose(); }Then in the DocumentCompleted method, I create the bitmap using WebBrowser’s DrawToBmp(...) method.
/// /// this.ThumbnailImage is a BitMap object /// this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height); webBrowser.BringToFront(); webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds); this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
Putting all together
Markup:
<%@ Page Language="C#" CodeBehind="~/Test.aspx.cs" Inherits="ActiveTest.Test" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtWebsiteAddress" runat="server" Text="www.google.com" /> <asp:Button ID="btnCreateThumbnailImage" runat="server" Text="Create Thumbnail Image" OnClick="CreateThumbnailImage" /></td> <asp:TextBox ID="txtWidth" runat="server" Text="200" /> <asp:TextBox ID="txtHeight" runat="server" Text="200" /> <asp:Image ID="imgThumbnailImage" runat="server" Visible="false" /> </div> </form> </body> </html>
Code:
public partial class Test : Page { bool snap = false; protected void CreateThumbnailImage(object sender, EventArgs e) { snap = true; } protected override void Render(HtmlTextWriter writer) { if (snap) { int width = Int32.Parse(txtWidth.Text); int height = Int32.Parse(txtHeight.Text); StringBuilder builder = new StringBuilder(); HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(builder)); base.Render(htw); string html = builder.ToString(); Thumbnail thumbnail = new Thumbnail(html, 800, 600, width, height, Thumbnail.ThumbnailMethod.Html); Bitmap image = thumbnail.GenerateThumbnail(); image.Save(Server.MapPath("~") + "/Thumbnail.bmp"); writer.Write(html); writer.Write("<img src=\"Thumbnail.bmp\" />"); } else base.Render(writer); } } public class Thumbnail { public enum ThumbnailMethod { Url, Html }; public string Url { get; set; } public Bitmap ThumbnailImage { get; set; } public int Width { get; set; } public int Height { get; set; } public int BrowserWidth { get; set; } public int BrowserHeight { get; set; } public string Html { get; set; } public ThumbnailMethod Method { get; set; } public Thumbnail(string data, int browserWidth, int browserHeight, int thumbnailWidth, int thumbnailHeight, ThumbnailMethod method) { this.Method = method; if (method == ThumbnailMethod.Url) this.Url = data; else if (method == ThumbnailMethod.Html) this.Html = data; this.BrowserWidth = browserWidth; this.BrowserHeight = browserHeight; this.Height = thumbnailHeight; this.Width = thumbnailWidth; } public Bitmap GenerateThumbnail() { Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); return ThumbnailImage; } private void GenerateThumbnailInteral() { WebBrowser webBrowser = new WebBrowser(); webBrowser.ScrollBarsEnabled = false; if (this.Method == ThumbnailMethod.Url) webBrowser.Navigate(this.Url); else webBrowser.DocumentText = this.Html; webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted); while (webBrowser.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents(); webBrowser.Dispose(); } private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser webBrowser = (WebBrowser)sender; webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight); webBrowser.ScrollBarsEnabled = false; this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height); webBrowser.BringToFront(); webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds); this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero); } }
How to serialize object to a string as XML and deserialize XML string to an object (Useful when saving multiple selections to database fileds like checkbox selections)
When saving values of fields where we have multiple selections, it is usual way to save as comma separated values in a text field in the database. However, this make extreamly hard to query and edit those values. So as an alternative way we can serialize the object to a string of XML and then save the string of XML to a XML database field where we can perform X-Path Queries. (For SQL Server X-Path - Please see this article). Then when retrieving values from the database, we can read the XML string from database and desrialize XML string in to our respective object.
This example demonstrate how to serialize and deserialize List<string> object to XML string and deserialize XML string to a List<string> object.
This example demonstrate how to serialize and deserialize List<string> object to XML string and deserialize XML string to a List<string> object.
protected override void OnLoad(EventArgs e) { base.OnLoad(e); List<string> values = new List<string>(); for (int i = 0; i < 10; i++) values.Add("Value " + i); string xml = this.Serialize(values); /// /// Save database as XML so that you can do a XPath Query /// /// /// Get xml string and convert it in to a List<string> /// List<string> savedValues = this.Deserialize(xml); } private string Serialize(List<string> values) { XmlSerializer serializer = new XmlSerializer(typeof(List<string>)); MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); serializer.Serialize(writer, values); stream = (MemoryStream)writer.BaseStream; UTF8Encoding utf8 = new UTF8Encoding(); string xml = utf8.GetString(stream.ToArray()); return xml; } private List<string> Deserialize(string xml) { XmlSerializer serializer = new XmlSerializer(typeof(List<string>)); UTF8Encoding utf8 = new UTF8Encoding(); byte[] bytes = utf8.GetBytes(xml); MemoryStream stream = new MemoryStream(bytes); XmlTextReader reader = new XmlTextReader(stream); List<string> values = (List<string>)serializer.Deserialize(reader); return values; }
How to send an email using Gmail in Asp.net and C#
string toAddress = "you@yahoo.com"; string fromAddress = "me@gmail.com"; string password = "myPassword"; MailMessage message = new MailMessage(fromAddress, toAddress); MailAddressCollection to = new MailAddressCollection(); to.Add(new MailAddress(toAddress)); message.Subject = "RE: Feedback"; message.Body = "A Test Eamil <br /> by using Gmail <hr /> Thanks"; message.IsBodyHtml = true; SmtpClient smtpSender = new SmtpClient(); smtpSender.Port = 587; smtpSender.Host = "smtp.gmail.com"; smtpSender.EnableSsl = true; smtpSender.Credentials = new System.Net.NetworkCredential(fromAddress, password); smtpSender.Send(message);
How to register User Control specific CSS and Java Scripts
It is always optimistic to include usercontrol specific CSS and JS files only when the UserControl renders it's contents.
CSS File:
I have CSS and JS files in the root of my web projects. If you would like to put then in diffrent folders you should specify the correct path along with the root url.
Then you can use Literral control to register the css and the ClientScript to register the JS files.
CSS File:
#userControlWrapper { width:400px; height:400px; border:solid 1px #f00; background-color:#aaa; } h1.Big { font-size:40px; }Markup:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl.ascx.cs" Inherits="ActiveTest.WebUserControl" %> <div id="userControlWrapper"> <h1 class="Big">User Control...</h1> </div>
I have CSS and JS files in the root of my web projects. If you would like to put then in diffrent folders you should specify the correct path along with the root url.
Then you can use Literral control to register the css and the ClientScript to register the JS files.
namespace ActiveTest { public partial class WebUserControl : UserControl { public string RootUrl { get { Uri requestUri = Context.Request.Url; HttpRequest request = Context.Request; string rootUrl = string.Format("{0}{1}{2}{3}{4}", requestUri.Scheme, Uri.SchemeDelimiter, requestUri.Host, requestUri.IsDefaultPort ? string.Empty : string.Format(":{0}", requestUri.Port), request.ApplicationPath); return rootUrl.EndsWith("/") ? rootUrl : string.Format("{0}/", rootUrl); } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); string styles = "<link href=\"{0}WebUserControl.css\" rel=\"stylesheet\" type=\"text/css\" />"; this.Page.Header.Controls.Add(new Literal() { Text = string.Format(styles, this.RootUrl) }); this.Page.ClientScript.RegisterClientScriptInclude(this.GetType().Name, string.Concat(this.RootUrl, "WebUserControl.js")); } } }
Tuesday, September 14, 2010
How to convert PDF document (custom object) to a byte array
string fileName = "application.pdf"; iTextSharp.text.Document doc = new iTextSharp.text.Document(); /// /// crate your pdf document /// System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); System.IO.MemoryStream stream = new System.IO.MemoryStream(); binaryFormatter.Serialize(stream, doc); byte[] bytes = stream.ToArray(); this.Response.Clear(); this.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", Path.GetFileName(fileName))); this.Response.ContentType = "application/pdf"; this.Response.BinaryWrite(bytes); this.Response.Flush(); this.Response.End();
Monday, September 13, 2010
How to create a popup window on the fly using java script in c# code behind
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head2" runat="server"> <title>Test Page</title> <script runat="server"> private string script = @" var popup = window.open('','', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no'); popup.document.write(""{0}""); "; private StringBuilder body = new StringBuilder(); protected override void OnLoad(EventArgs e) { base.OnLoad(e); /// /// build your html document here /// body.Append("<html>"); body.Append("<head></head>"); body.Append("<body>"); body.Append("<h1>Hello World</h1>"); body.Append("<p>This is a popup window created on the fly"); body.Append("</body>"); } protected void OpenWindow(object sender, EventArgs e) { /// /// Check your condition /// bool myCondition = true; if (myCondition) { this.ClientScript.RegisterClientScriptBlock( this.GetType(), this.GetType().Name, string.Format(this.script, this.body.ToString()), true); } } </script> </head> <body> <form id="form2" runat="server"> <asp:LinkButton runat="server" ID="lnkButton" OnClick="OpenWindow" Text="Open a Window" /> </form> </body> </html>
Thursday, September 09, 2010
How to hide page elements while printing
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <style type="text/css" media="print"> #topNavigation { display:none; } #footer { display:none; } </style> </head> <body> <form id="form1" runat="server"> <div> <div id="topNavigation"> Top Navigation </div> <div id="content"> Content </div> <div id="footer"> Footer </div> </div> </form> </body> </html>
How to restart a asp.net web application using button click
<%@ Page Language="C#" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <script runat="server"> protected void Stop(object sender, EventArgs e) { bool error = false; try { HttpRuntime.UnloadAppDomain(); } catch { error = true; } if (!error) return; string ConfigPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "\\web.config"); try { File.SetLastWriteTimeUtc(ConfigPath, DateTime.UtcNow); } catch { // // Cant shut down // } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Button runat="server" ID="btnStop" OnClick="Stop" Text="Stop" /> </div> </form> </body> </html>
Subscribe to:
Posts (Atom)
Azure Storage Account Types
Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...
-
Demo: I was thinking a way to show images before actually uploading them to server. I would say to preview images using javascript. Obv...
-
Demo : I am using asp.net UpdatePanel control to partial page update. As there is no keyup event for the asp.net TextBox control, I add an ...