How to show alert from separate code module in asp.net - asp.net

How do you show an alert from a separate code moduel in asp.net, not the codebehind of a page, thats an easy one.
This is one way to do it from the code behind of a page.
ScriptManager.RegisterStartupScript(Page, Me.GetType, "alert('Hello')", True)
How can i achieve this from a separate code module though, i am not sure. it needs a control and control type for the first to parameteres respectively. So the code above will error out on the first 2 params. Does anyone have a solution?

You need to pass the Page object of the current request to this extern module. Then you can use it in the RegisterStartupScript function. For example:
Some extern class:
Public Class MyClass
Public Shared Sub DoSomething(Page As Page)
' do something
ScriptManager.RegisterStartupScript(Page, Page.GetType, "alert('Hello');", True)
End Sub
End Class
In theaspx page or CodeBehind:
' ...
MyClass.DoSomething(Page)
' ...

Related

Access winform variable from browsercontrol

I have an application in ASP.Net Ajax. I want to open it via a browsercontrol from a winform, and I wish to access a variable (username) that the user used to log in to the webform with. On load I would like to read that username and perform the rest of my webpage code on that browsercontrol using that username.
My ASP.Net Ajax has been published to a internal web server and the browsercontrol loads that IP address.
Is there any way to achieve this at all?
EDIT:
I have discovered the javascript extension: window.external
And I can call a C# procedure from the webpage using javascript with it, which is a start, but I need to retrieve a varaible from c# - this is where the problem comes in. I have tried the
var name = function window.external.GetGlobalVariable(MyGlobalProcedure, "Cannot Get Value");
But javascript error says the method cannot be applied to the object.
Your answer should be as follows:
Public Class Form1
Dim GlobalVar As String = "Your Name"
Dim YourBrowser As New WebBrowser
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
YourBrowser.Url = New Uri("Your URL address")
AddHandler YourBrowser.DocumentCompleted, AddressOf PageLoadComplete
End Sub
'The invokescript will only work once the HTML has finished loading itself into your WebBrowser
Sub PageLoadComplete()
'Must declare the string inside an array as the invokescript only allows an object to be sent
Dim VarToSend As String() = {GlobalVar}
YourBrowser.Document.InvokeScript("yourJavascriptfunction", VarToSend)
End Sub
The javascript section should look as follows:
<script type="text/javascript" language="javascript">
function userNameSet(name) {
$(document).ready(function() {
//variable now exists inside your WebBrowser client and can be used accordingly now
alert(name);
});
}
</script>
References for answer: http://www.dotnetcurry.com/showarticle.aspx?ID=194
"Store that name in a session variable and access the session in your ajax call"
In your ASP.Net application create a hidden field (or if it's somewhere on the UI in some control that works also). Put the username or whatever information you want to share into that field.
From your WinForms program you can request that field through the WebBrowser control like this:
MessageBox.Show(WebBrowser1.Document.GetElementById("txtUsername").GetAttribute("value"))
The above assumes you have some HTML element called txtUsername with the value attribute set.

Grabbing a property from an aspx page to an ascx toolbar in VB

I have a web page (aspx)- Purchasing page, with a ascx toolbar - Export Toolbar, that is used to export the data (either .xls or .csv).
I need to grab the Name of the Supplier from the Purchasing page and insert that value into the name of the export file on the ascx toolbar.
On the Purchasing page there is a ddl where the user can select the supplier and a grid that will display all the data. Above the grid there is the tool bar with an export button. I need to be able to grab the text of the dropdown list and utilize that on the ExportToolbar.ascx.vb page so I can take that text and insert it into the name.
I was trying to use a public property get and set method but it was not working. How would I go about grabbing that selected text from the Supplier ddl?
Conventional thinking goes like this: an ascx can be hosted on any aspx page. So usually it is bad form for an ascx to access properties of its host page. It is much more proper for the ascx to have a public property and the aspx will push the value into the ascx (as needed).
However, if you really want to go this route, the .Page property (of the ascx) referrs to the host page. If you cast it to the (stronger) type(name) of the host, you can get to the hosts properties. Like this:
'if your host page is called HostPage (and the class name is the same)
Dim host as HostPage = CType(me.Page, HostPage)
'now refer to the controls on the host (aspx) page
dim example as string
example = host.txtExample.Text
Keep in mind, this will cause errors if your ascx is hosted on several pages.
You can use an event form this purpose. Define the event on the UserControl like this:
Public BeforeExportEventArgs
Inherits EventArgs
Public Property FileName As String
End Class
Public Class ToolbarControl
Inherits UserControl
Public Event BeforeExport As EventHandler(Of BeforeExportEventArgs)
Public Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
' Retrieve File Name
Dim beforeExpEventArgs As New BeforeExportEventArgs()
RaiseEvent BeforeExport(Me, beforeExpEventArgs)
' Set default filename if not provided by an event handler
If String.IsNullOrEmpty(beforeExpEventArgs.FileName) Then
beforeExpEventArgs.FileName = "DefaultFileName.csv"
End If
' Export data
End Class
Add an event handler to the form that hosts the UserControl:
Public Class WebForm1
Inherits Page
' ...
Public Sub expToolbar_BeforeExport(sender As Object, e As BeforeExportEventArgs) Handles expToolbar.BeforeExport
e.FileName = ddlSupplier.Text + ".csv"
End Sub
' ...
End Class
This way, you avoid tight coupling between the UserControl and the Page. The pages that host the UserControl can set a specific filename, but don't have to.
What I ended up doing was this-
On the ascx page I created a public property-
Public Property SupplierSelection As String
Get
Return Convert.ToString(ViewState.Item("SupplierSelection"))
End Get
Set(ByVal value As String)
ViewState.Add("SupplierSelection", value)
End Set
End Property
And then on the aspx page I added this on the load grid event-
SupergridToolbar1.SupplierSelection = ddlStrategy.SelectedItem.Text.ToString()
I was then able to use the Supplier Selection on the ascx page. Thanks for the help!

Getting a ScriptReference from a ScriptResourceMapping definition in a custom control

I am building a custom control with client side scripts that I would like to reference using ScriptManager.ScriptResourceMapping (to make use of the Path and DebugPath attributes).
I would like the custom control to be easily ported to other projects - i.e. I would like to drag and drop the codebehind files (and eventually make the control a separate DLL, but for now the drag and drop will suffice). I would therefore like to avoid (1) having the client script as an embedded resource, (2) referenced as a WebResource in the AssemblyInfo, or (3) have the ScriptManager.ScriptResourceMapping.AddDefinition in global.asax.
In simple terms can I get the script management code to be in just the custom control's code?
At the moment I am getting an error stating that the script reference cannot be found in the assembly, and I guess I am setting the wrong assembly.
My custom control code is as follows:
Public Class MyControl
Inherits System.Web.UI.LiteralControl
Implements ISectionControl, IScriptControl
Private _scriptReference As ScriptReference
Public Sub New()
' Add the resource mapping
ScriptManager.ScriptResourceMapping.AddDefinition("MyControlScript", New ScriptResourceDefinition With {
.ResourceAssembly = System.Reflection.Assembly.GetExecutingAssembly,
.ResourceName = "MyControlScript.js",
.Path = "Path.To.MyControlScript.minimised.js",
.DebugPath = "Path.To.MyControlScript.original.js"
})
' Set the script reference
_scriptReference = New ScriptReference("MyControlScript.js", Assembly.GetExecutingAssembly.FullName)
End Sub
Protected Overrides Sub OnPreRender(e As System.EventArgs)
MyBase.OnPreRender(e)
' Register the script
ScriptManager.GetCurrent(Page).RegisterScriptControl(Of MyControl)(Me)
' Some code to set the Text of the literal control
' ...
End Sub
Public Function GetScriptDescriptors() As System.Collections.Generic.IEnumerable(Of System.Web.UI.ScriptDescriptor) Implements System.Web.UI.IScriptControl.GetScriptDescriptors
Return New ScriptDescriptor() {}
End Function
Public Function GetScriptReferences() As System.Collections.Generic.IEnumerable(Of System.Web.UI.ScriptReference) Implements System.Web.UI.IScriptControl.GetScriptReferences
Return New ScriptReference() {_scriptReference}
End Function
End Class
I hope the question makes sense. Thanks for taking the time to read through.
Ali
Answered this myself, I was getting confused with the assemblies and the constructors for ScriptReference. I just wanted a ScriptReference with the (mapped) name so I used the blank constructor and then set Name. I could then remove the assembly information.
Adjusting the following sorted the problem out:
Public Sub New()
' Add the resource mapping
ScriptManager.ScriptResourceMapping.AddDefinition("MyControlScript", New ScriptResourceDefinition With {
.Path = "Path.To.MyControlScript.minimised.js",
.DebugPath = "Path.To.MyControlScript.original.js"
})
' Set the script reference
_scriptReference = New ScriptReference() With {.Name="MyControlScript"}
End Sub

Response.Redirect to Class that inherits from UI.Page?

everyone, thank for your time.
Well this my problem (well it's not a probleam at all), it is possible to have a class that inherits from ui.page and then instance an object of that class and do a redirect to it ?
Something like this:
Public sub myMethod()
Dim myPage as new myClassThatInheritsFromUIPage()
Response.redirect(myPage) 'Here is one of my "no-idea" line
end sub
I do this in my webForm (and that what I want to do in a class that inherits from ui.page):
Response.BufferOutput = True
Response.ClearContent()
Response.ClearHeaders()
ostream=crReportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat)
Response.AppendHeader("Cache-Control", "force-download")
Response.AppendHeader("Content-disposition","attachment;filename=ReportAsPDF.pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(ostream.ToArray())
Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
What I want to do is perfectly possible with a normal WebForm, but my webForm doesn't render nothing at all (at least as (x)html so, that's because I would like to know if what I'm asking is possible to achieve.
Thank you everyone.
Well at the end I just add "HttpContext.Current." to all the lines that include a "response" attribute, so now I have just a class that NOT inherits from "UI.Page" and just call the method that clear the buffer (a custom method), add the headers (to force the download,set the mime type and filename) and flush the response by itself and get the effect/use I want it.
In order to access to the Session vars just add "HttpContext.Current." and it works, I don't know how secure or if is a good way,but appears to work well.
So the code now looks something like this:
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports CrystalDecisions.ReportSource
Namespace foo
Public Class requestReport
'just to instance the object'
Public Sub New()
End Sub
Public Sub downloadReport()
'do all the stuff to connect and load the report'
HttpContext.Current.Response.BufferOutput = True
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ClearHeaders()
ostream=crReportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat)
HttpContext.Current.Response.AppendHeader("Cache-Control", "force-download")
HttpContext.Current.Response.AppendHeader("Content-disposition","attachment;filename=ReportAsPDF.pdf")
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.BinaryWrite(ostream.ToArray())
HttpContext.Current.Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
End Sub
End Class
End Namespace
And from a command for example do this:
dim myReport as new foo.requestReport()
myReport.downloadReport()
Of course now you can add more attributes or method if you need it.
So now I don't even don't use Response.redirect() or inherits from "UI.Page", just a class that "change" the "current response" and "flush" the content created on fly with the crystal report, I think I was kind of totally lost but your answers really help me, especially what Tejs says, what is almost the same or the same what I just did. Thank you.
UPDATE:
By the way, I just realize that the ReportDocument class has this method: ExportToHttpResponse that let us flush the Crystal Report to the browser as PDF/XSL etc forcing (or not) the download of the file.
No, as there is no current overload that accepts a UI.Page instance. However, you could call the Render method on your new page and write directly to the response stream. AKA
Clear the Response Buffer.
Render your page instance to the response buffer.
Invoke Response.End() to flush the request and send it to the client.
If your new page doesnt actually do anything, you can additional just send no content back with the response.
You can use Server.Transfer and pass in the instance of the page object that you want to tranfer to.
Here is the documentation: HttpServerUtility.Transfer
Try just doing this instead:
HttpContext.Current.Response.Redirect("...");
HttpRequest Request = HttpContext.Current.Request;
HttpResponse Response = HttpContext.Current.Response;
And after that you can redirect any page.

Need to reference controls/properties in an ascx control (asp.net, written in vb)

I have a user control that I'm adding to a webpage dynamically. The ascx has a couple of controls that I want to have access to at runtime. I can access the ascx itself, but none of the controls on the ascx are available. I have tried adding a simple public variable and also tried adding a public property to the ascx, but I am unable to get access to either of them at design time (compile errors). I would appreciate any ideas - I'm stuck... :-)
I added the following to the code-behind of the ascx control:
Public Property areaCode() As String
Get
Return iebEmpPhoneAreacode.Text
End Get
Set(ByVal value As String)
iebEmpPhoneAreacode.Text = value
End Set
End Property
Public AreaCodeStr As String = ""
and am trying to use variations of the following to access the property/ascx controls:
For Each ctrl As Control In pnlPhones.Controls
If ((TypeOf ctrl Is ctrlPhone) And (ctrl.ID = vbNullString)) Then
(DirectCast(ctrl, ctrlPhone)).AreaCodeStr = "test"
'or try this
ctrl.areaCode = "test"
End If
Next
The hosting page should have an #Reference Directive pointing to the loaded ascx so it will be compiled with the page.
Something like:
<%# Reference VirutalPath="YourReferenceControl.ascx" %>
This should go in the directives area somewhere below the #Page directive.
http://msdn.microsoft.com/en-us/library/w70c655a.aspx

Resources