Sunday, February 10, 2013

Create dll libary include with ascx or aspx

Building Re-Usable ASP.NET User Control and Page Libraries with VS 2005 

http://weblogs.asp.net/scottgu/archive/2005/08/28/423888.aspx

 

Turning an .ascx User Control into a Redistributable Custom Control

http://msdn.microsoft.com/en-us/library/aa479318.aspx

 

Background

Since its early days, ASP.NET has always supported two different ways of authoring server controls:
  1. Custom controls: These are controls written from scratch exclusively using code. Essentially, you write a class that extends Control (directly or indirectly), and you take care of everything. You need to write logic to create child controls that you want to use, and you override the Render method to perform rendering. Typically, you build this control into a redistributable assembly (that is, a DLL), which can then be used by any ASP.NET applications, simply by placing the assembly in the "bin" directory of the application (or in the Global Assembly Cache).
  2. User controls: These controls are written using an .ascx file, which looks much like an aspx page. That is, you can simply drag and drop the UI elements that you want to use into the design surface. You don't need to worry about control creation, nor about overriding the Render method.
These two methods are very different, and each has a number of advantages and disadvantages. I won't discuss them all, but will focus on those that are relevant to this article:
  • Custom controls require a lot of development expertise to be written, while user controls are authored using an advanced designer, and are much more approachable. For this reason, user controls typically take a lot less time to write.
  • Custom controls can easily be redistributed without having to give away their sources. On the other hand, user controls are always used based on an ascx text file, making it less ideal for reuse across applications.
The goal of this article is to show how you can have the best of both worlds by turning an ascx user control into a redistributable custom control, by making use of the new ASP.NET precompilation features.

Brief Outline of the Steps

The basic steps to make this happen are as follows:
  1. Write your user control as you normally would, typically using the Visual Studio designer.
  2. Test it using a simple page before trying to deploy it.
  3. Deploy the application to precompile it.
  4. Grab the user control's assembly produced by the deployment step, and you're essentially done: You have your custom control.
  5. Finally, use your custom control in other apps the same way as you always use custom controls.
We will look at those steps in more detail in the rest of the article.

Step 1: Authoring the User Control

To author the user control, it is best to start with an empty app that contains nothing other than the ascx. While the authoring of the user control uses "standard" techniques, there are some restrictions that you need to be aware of in order for it to be successfully turned into a standalone custom control.
The main restriction is that the user control needs to be self-contained. That is, it cannot be dependent on app global things like App_Code or global.asax. The reason for this is that since the goal is to turn the UserControl into a standalone DLL, it would break in other apps if it relied on code that is not part of that DLL. One exception to this rule is that the UserControl can be dependent on assemblies that live in the bin directory (or in the GAC). You just have to make sure that the other assemblies are always available when you use your custom control in other apps.
Another tricky thing is the use of static resources, such as images. After you turn it into a custom control in a standalone assembly, it becomes hard for it to keep such references, and avoiding them simplifies deployment. If you really must have such references, one option is to use absolute URLs if you can guarantee that the resource will always be available on a certain site. Or you can look into machine wide resources (e.g., src="/MyImages/welcome.jpg"), though you will then need to make sure the resources are installed on the server machine (e.g. as part of some setup).
So let's start and actually author the user control. Visual Studio 2005 gives you the choice to place the code in a separate file, or use inline code. This is a matter of personal preference, and either one will work to create a custom control. For this article, we will use inline code. When you create the user control (say MyTestUC.ascx), Visual Studio creates it with the a @control directive that looks like this:
<%@ControlLanguage="C#"ClassName="MyTestUC"%> 

This is fine, except for one thing: we want the class to live within a namespace of our choice (instead of "ASP", which is used by default). To do this, we simply modify the ClassName attribute to include the namespace (this is a new feature in 2.0). Here's an example:
<%@ControlLanguage="C#"ClassName="Acme.MyTestUC"%> 

That's really the only "special" thing you need to do. Now you can go ahead and implement your user control as you always would: add some server control, some client HTML, server script, client script, and so on.

Step 2: Testing Your User Control

Before trying to turn the user control into a custom control, it is a good idea to test it in the source app using a simple page. To do this, simply create a new Page in Visual Studio, go to design View, and drag and drop your user control into it.
The two notable pieces of your page are the Register directive:
<%@RegisterSrc="MyTestUC.ascx"TagName="MyTestUC"TagPrefix="uc1"%>
and the user control declaration:

Note that at this point, the Register directive uses the user control syntax (Src/TagName/TagPrefix) and not the custom control syntax (TagPrefix/Namespace/Assembly). This will change after we turn the user control into a custom control.
Run your page (press CTRL-F5) and make sure the user control works the way you want before moving to the next step.

Step 3: Use the Publish Command to Precompile the Site

The next step is to use the new Publish command to precompile your site and turn your user control into a potential custom control. You'll find the command under Build / Publish Web Site. In the Publish dialog, do the following:
  • Pick a Target Location. This is the location on your hard drive that your site will be precompiled to.
  • Deselect "Allow this precompiled site to be updatable". In updatable mode, only the code behind file (if any) would get compiled, and the ascx would be left unprocessed. This is useful in some scenarios, but is not what you want here since you want the resulting DLL to be self-contained.
  • Select "Use fixed naming and single page assemblies". This will guarantee that your user control will be compiled into a single assembly that will have a name based on the ascx file. If you don't check this option, your user control could be compiled together with other pages and user controls (if you had some), and the assembly would receive a random name that would be more difficult to work with.
Though it is entirely optional, note that the Publish Web Site dialog lets you strongly name the generated assemblies. This allows you to sign the assembly so that it cannot be tampered with. Additionally, it allows you to place the assemblies in the Global Assembly Cache (GAC), which makes it easier to use machine-wide. I will provide more information on this in Step 5.
Go ahead and complete the dialog, which will perform the precompilation.
Note   This same step can also be accomplished without using Visual Studio by using the new aspnet_compiler.exe command-line tool. The options it supports are basically the same as what you see in the Publish dialog. So if you are more command-line inclined, you might prefer that route. For example, you would invoke it using the command:
aspnet_compiler -p c:\SourceApp -v myapp -fixednames c:\PrecompiledApp
.

Step 4: Finding the Resulting Custom Control

Now, using the Windows Explorer or a command-line window, let's go to the directory you specified as the target so we can see what was generated. You will see a number of files there, but let's focus on the one that is relevant to our goal of turning the user control into a custom control.
In the "bin" directory, you will find a file named something like App_Web_MyTestUC.ascx.cdcab7d2.dll. You are basically done, as this file is your user control transformed into a custom control! The only thing that's left to do is to actually use it.
Note   In case you're curious, the hex number within the file name (here
cdcab7d2
) is a hash code that represents the directory that the original file was in. So all files at the root of your source app will use
cdcab7d2
, while files in other folders will use different numbers. This is used to avoid naming conflicts in case you have files with the same name in different directories (which is very common for default.aspx!).

Step 5: Using Your New Custom Control

Now that we have created our custom control, let's go ahead and use it in an app. To do this, create a new Web application in Visual Studio. We then need to make our custom control available to this application:
  • In the solution explorer, right-click on your application, and choose Add Reference.
  • In the Add Reference dialog, choose the Browse tab.
  • Navigate to the location of your custom control (App_Web_MyTestUC.ascx.cdcab7d2.dll) and select it. It will be copied to the bin directory of your new app.
Note   as an alternative, you can choose to place the assembly in the GAC instead of the "bin" directory. In order to do this, you need to choose the Strong Name option in Step 3. You then need to add your assembly in the section of web.config in the Web application that requires it (or in machine.config to make to globally usable).
Create a test page that uses the custom control. This is similar to Step 2, except that you are now dealing with a custom control instead of a user control.
First, add a Register directive to your page. It should look something like this:
<%@RegisterTagPrefix="Acme"Namespace="Acme"Assembly="App_Web_mytestuc.ascx.cdcab7d2"%> 
Note how we are using a different set of attributes compared to Step 2. Recall that in Step 1, we made sure that the ClassName attribute included a namespace. This is where it becomes useful, as custom control registration is namespace-based. Also, you need to specify the assembly name, which is why having a name that is easily recognizable is useful, as discussed in Step 3.
Declare a tag for the custom control, for example:
 
That's it, you can now run your app (CTRL-F5), and you are using your new custom control!
This shows how to use your custom control declaratively, but note that it can also be used dynamically, just like any other control. To do this, just create the control using "new". Here is what the previous sample would look like using dynamic instantiation:
<%@PageLanguage="C#"%>








Note   Instantiating your custom control dynamically as described above is basically the equivalent of instantiating your original user control using the LoadControl API. Note that you can no longer use the standard LoadControl API after converting it to a custom control, since custom controls don't have a virtual path. However, ASP.NET 2.0 has a new LoadControl override that takes a Type that you could use in this case. The one reason I can think of that you might choose to call LoadControl instead of just using "new" is to take advantage of fragment caching (also called partial caching). If you use "new", any OutputCache directive in your ascx will be ignored.

 

Wednesday, December 19, 2012

Google Plus Share not picking og image

Simply because the image should be

The height must be at least 120px, and if the width is less than 100px, then the aspect ratio must be no greater than 3.0

http://stackoverflow.com/questions/9103504/why-does-google-ignore-my-1-page-thumbnail

Tuesday, May 1, 2012

How to Export GridView To Word/Excel/PDF/CSV in ASP.Net 

 

http://www.aspsnippets.com/Articles/Export-GridView-To-WordExcelPDFCSV-in-ASP.Net.aspx



Restore POP3 Mail to the Server

COPY FROM SOURCE: http://www.slipstick.com/outlook/email/restore-pop3-mail-server/

Using IMAP to restore mail to the server

When you email account supports IMAP, you can restore mail to the server in a few simple steps:
  1. Create a second email account in your profile using the IMAP account type.
  2. You'll now have two accounts in your profile for the same email account, with the IMAP account adding a second *.pst to the profile.
  3. Make sure you set the POP3 account to leave mail on the server in the account's More Settings. Advanced dialog.
  4. Drag the messages from the POP3 Inbox to the IMAP folder's Inbox.
  5. Tip: You may want to start with about 100 messages at a time and wait a minute or so for the messages to sync up. If it works well, select a larger block of messages to move in the second batch.
  6. The messages will be synced with the mailbox on the server.
  7. When finished, remove the IMAP account from the profile. (unless you want to use it instead of POP3.)
Gmail: configure the account for IMAP in your GMAIL settings then setup the email account in Outlook. Gear icon, Mail settings, Forwarding and POP/IMAP link)
Yahoo: use imap-ssl.mail.yahoo.com for the IMAP server name. In Outlook 2007 and 2010 you need to create the account manually.
Hotmail: although Hotmail does not support IMAP, you can use the Outlook Hotmail Connector to upload mail to the server.
Note that both Gmail and Hotmail make it difficult for Outlook to delete mail from the server. If Outlook deleted downloaded email from either account, check your settings in the account online and configure it to archive mail downloaded using POP3.

If your mail server doesn't support IMAP

If your email account does not support IMAP, you can't easily restore mail to the server unless it can POP email from other servers. In this case, you could upload the mail to another server then POP it back to your original email account. If this is not possible and you need online access to the mail you downloaded, consider using Gmail, Hotmail, or Yahoo to store it online for you.
If your account can collect mail from POP accounts (like Gmail, Yahoo and Hotmail do), you can upload the mail using IMAP then your account can collect it using POP3. Before using this method, verify your POP3 account can collect mail from the IMAP server - GMail and Hotmail require SSL for POP3 services and many accounts do not use SSL when "popping" accounts.
  1. Create an account that supports both POP3 and IMAP.
  2. Use the instructions above to put the mail online.
  3. Go to your mail account's web access and configure the account to collect POP mail from the new account.
  4. Once the messages are back online in your mailbox, delete the POP account from the online configuration and the IMAP account from Outlook.

Restoring Exchange Server mail to the server

If this happens with an Exchange server account, set the Exchange account as the default delivery location and drag any mail that does not resync with the Exchange mailbox back to the mailbox.

 

Wednesday, June 29, 2011

state lost Dynamic control in asp.net

every time dynamic control
you have responsibility to recreate when post back. that 's the reason state and data lost

Monday, June 27, 2011

Handle Dynamic button click event ASP.NET

Dim btnConfig As New Button
btnConfig.ID = "Config" + dr("confignum").ToString
btnConfig.Text = dr("configname")
btnConfig.CommandName = "ShowPart"
btnConfig.CommandArgument = dr("confignum")
btnConfig.CssClass = "SingleConfigBtn"
AddHandler btnConfig.Command, AddressOf btnConfig_Click
plcConfigList.Controls.Add(btnConfig)

Sub btnConfig_Click(ByVal send As Object, ByVal e As CommandEventArgs)
showPartList(e.CommandArgument) 'dr("confignum") in this case will be received
End Sub

Thursday, September 16, 2010

Editable sitemap provider and Solve Space querystring bug

Imports System
Imports System.Data
Imports System.Configuration
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Web.Configuration
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Xml

'''
''' Extends the XmlSiteMapProvider class with edit functionality
''' Requires all siteMapNodes to have unique titles.
'''

Public Class EditableXmlSiteMapProvider
Inherits XmlSiteMapProvider

Public Sub New()
End Sub

Public Shadows Sub AddNode(ByVal parentTitle As String, ByVal title As String, ByVal url As String, ByVal roles As String)
Dim doc As XmlDocument = LoadXmlDoc()
Dim parent As XmlElement = FindNodeByTitle(doc, parentTitle)

Dim newChild As XmlElement = doc.CreateElement("siteMapNode")
newChild.SetAttribute("url", url)
' url must go in lower case to get xpath to work
newChild.SetAttribute("title", title)
' url must go in lower case to get xpath to work
newChild.SetAttribute("roles", roles)
parent.AppendChild(newChild)
SaveXmlDoc(doc)

End Sub

Public Sub UpdateNode(ByVal originalTitle As String, ByVal newParentTitle As String, ByVal title As String, ByVal url As String, ByVal roles As String)
Dim doc As XmlDocument = LoadXmlDoc()
Dim node As XmlElement = FindNodeByTitle(doc, originalTitle)

node.SetAttribute("url", url)
' url must go in lower case to get xpath to work
node.SetAttribute("title", title)
' url must go in lower case to get xpath to work
node.SetAttribute("roles", roles)

' check if the parent has changed
If node.ParentNode.Attributes("title").Value <> newParentTitle Then
node.ParentNode.RemoveChild(node)

' find the new parent
Dim newParent As XmlElement = FindNodeByTitle(doc, newParentTitle)
newParent.AppendChild(node)
End If
SaveXmlDoc(doc)
End Sub

Public Sub DeleteNode(ByVal title As String)
Dim doc As XmlDocument = LoadXmlDoc()
Dim node As XmlElement = FindNodeByTitle(doc, title)
node.ParentNode.RemoveChild(node)
SaveXmlDoc(doc)
End Sub

Private Function LoadXmlDoc() As XmlDocument
Dim doc As New XmlDocument()
doc.Load(HttpContext.Current.Server.MapPath(FilePath))
Return doc
End Function

Private Sub SaveXmlDoc(ByVal doc As XmlDocument)
Dim AbsPath As String = HttpContext.Current.Server.MapPath(FilePath)
Try
doc.Save(AbsPath)
Catch ex As UnauthorizedAccessException
Try
' try to remove 'read-only' attribute on the file.
'WebUtil.RemoveReadOnlyFileAttribute(AbsPath)
doc.Save(AbsPath)
Catch
' throw the original exception
Throw ex
End Try
End Try
MyBase.Clear()
MyBase.BuildSiteMap()
End Sub

Private Function FindNodeByTitle(ByVal doc As XmlDocument, ByVal title As String) As XmlElement
Dim xPath As String = [String].Format("//*[@title='{0}']", title)
Dim node As XmlElement = TryCast(doc.SelectSingleNode(xPath), XmlElement)
If node Is Nothing Then
Throw New Exception("Node not found with title: " & title)
End If
Return node
End Function

'''
''' The built in SiteMapNode.Url property gives a different value to the actual web.sitemap value,
''' it is a mapped value that changes depending on the v.dir of the running web site.
''' This method reads the xml attribute direct from the web.sitemap file.
'''

Public Function GetActualUrl(ByVal title As String) As String
Return Me.FindNodeByTitle(LoadXmlDoc(), title).Attributes("url").Value
End Function

Public Shared ReadOnly Property FilePath() As String
Get
' if anyone gets a nicer method to read the web siteMapFile attribute, please post it. i tried using 'System.Web.Configuration but i couldn't get it working. also, the site breaks when running off VS web server 'because of 'cannot read IIS metabase' errors.
Dim webConfigText As String = File.ReadAllText(HttpContext.Current.Server.MapPath("~/web.config"))
Dim m As Match = Regex.Match(webConfigText, "siteMapFile=""(.*?)""", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
If Not m.Success Then
Return "~/Web.sitemap"
Else
' default value. otherwise we could throw new Exception("web.config does not contain a siteMapFile element");
Return m.Groups(1).Captures(0).Value
End If
End Get
End Property

Public Overrides Function FindSiteMapNode(ByVal context As System.Web.HttpContext) As System.Web.SiteMapNode
Dim node As SiteMapNode = MyBase.FindSiteMapNode(context)

If node Is Nothing Then
If context Is Nothing Then
Return Nothing
End If

Dim queryString As String = CType(context.CurrentHandler, Page).ClientQueryString

Dim pageUrl As String = HttpUtility.UrlDecode(context.Request.Path & "?" & queryString)
node = MyBase.FindSiteMapNode(pageUrl)
End If

Return node
End Function
End Class