add client script to asp.net page dynamically - asp.net

I want to add javascript to asp.net page dynamically.
can anybody point me towards working example?
i know it can be done by using Page.ClientScript.RegisterClientScriptBlock
but i have no idea to use it.

MSDN
This is the MSDN link
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page), "Utils"))
{
string UtilsScript = ResourceHelper.GetEmbeddedAssemblyResource("Utils.js");
this.Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Utils", UtilsScript, true);
}
I added the above example to help,
Here we test if the script is already registered (using the type an dkey we register against) get the script as a string from an embedded resource, then register (the last parameter of true tells the code to render Script tags).
hope this helps
P

An example to move the value of a Drop Down List to text field. The ID parameters are the Object.ClientID properties for the drop down list and text box.
Private Sub RegisterClientDropDownToTextBox(ByVal functionName As String, ByVal dropDownId As String, ByVal textBoxId As String)
Dim javascriptFunction As String = "function " & functionName & "() {" & _
"document.getElementById('" & textBoxId & "').value = document.getElementById('" & dropDownId & "').value;" & _
"}"
Dim javascriptWireEvent As String = "document.getElementById('" & dropDownId & "').onclick = " & functionName & ";"
Me.ClientScript.RegisterClientScriptBlock(Me.GetType(), functionName & "_ScriptBlock", javascriptFunction, True)
Me.ClientScript.RegisterStartupScript(Me.GetType(), functionName & "_Startup", javascriptWireEvent, True)
End Sub

Related

Creating a webservice that accepts XML as a string

I have been trying to create a webservice that needs to allow the client to send thru 3 parameters being Username, Password and XML_In all 3 of type string. This then sends the variables to a Stored procedure which processes the data and returns an XML string which is then returned to the client.
The Stored procedure works 100% but I'm getting an error with the XML being sent thru as a string. From reading up most gave the suggestion of adding <httpRuntime requestValidationMode="2.0"/> and <pages validateRequest="false"> to my web.config which works but that would then apply to my entire site which I dont want at all.
The other suggestion was to place it in the #Page part but that does not apply to a web service as it has no user defined layout. Please see my code below and help. I'm still quite a newbie to .Net thus the reason I'm doing 90% of it in SQL.
The error That gets returned is :
System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (XML_In="<senddata><settings ...").
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
at System.Web.HttpRequest.ValidateHttpValueCollection(HttpValueCollection collection, RequestValidationSource requestCollection)
at System.Web.HttpRequest.get_Form()
at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
here's the code:
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Xml
Imports JumpStart.Framework.Database
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://mydomainname.co.za/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class LeadProcessor
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function Lead_Processing(ByVal UserName As String, ByVal PassWord As String, ByVal XML_In As String) As XmlDocument
Dim poDSL As New DSL
Dim Result As String
Dim XML_Out = New XmlDocument()
Result = poDSL.ExecuteProcedure_ExecuteScalar("DECLARE #Result XML " & _
"EXEC [dbo].[APP_InsertLeadFromXML] " & _
"#Username = N'" & UserName & "', " & _
"#Password = N'" & PassWord & "', " & _
"#ParmListXML = '" & XML_In.ToString & "', " & _
"#XMLResult = #Result OUTPUT " & _
"SELECT #Result")
XML_Out.LoadXml(Result)
Return XML_Out
End Function
I agree with CodeCaster comment (new projects - WCF or WebApi).
But if you can't change it now, consider use a XMLDocument as parameter, or an XElemento, or directly, do a Base64 transform of the text, in order to avoid that errors.
Code for your service' client:
your_proxy.Lead_Processing(sUserName, sPassWord, Convert.ToBase64String(Encoding.UTF8.GetBytes(sXML))
Then, in your service, do this
<WebMethod()> _
Public Function Lead_Processing(ByVal UserName As String, ByVal PassWord As String, ByVal XML_In As String) As XmlDocument
Dim oData As Byte() = Convert.FromBase64String(XML_In)
Dim sDecodedXML As String = System.Text.Encoding.UTF8.GetString(oData)
Dim poDSL As New DSL
Dim Result As String
Dim XML_Out = New XmlDocument()
Result = poDSL.ExecuteProcedure_ExecuteScalar("DECLARE #Result XML " & _
"EXEC [dbo].[APP_InsertLeadFromXML] " & _
"#Username = N'" & UserName & "', " & _
"#Password = N'" & PassWord & "', " & _
"#ParmListXML = '" & sDecodedXML & "', " & _
"#XMLResult = #Result OUTPUT " & _
"SELECT #Result")
XML_Out.LoadXml(Result)
Return XML_Out
End Function
Hope it helps
Edit:
Your service with base64.
We're telling that Asmx it's almost a legacy tech. New projects may use WCF tech (I can't teach you WCF in a few lines).
You can put that code into your asmx service. You can use that code in the way I edited my answer.

Dictionary(Of String, String) Cannot Evaluate Expression

When calling a Sub to populate a System.Collections.Generic.Dictionary with keys and values from a DictionaryEntry(), upon examining the Dictionary in Debug mode every property has a red circle with an X and contains the text "Unable to evaluate expression." It appears to be working, it will even complain if I try to add two entries with the same Key/Value pair. No keys or values are present either, even though my test string (valuesString) is populated.
I am calling the Sub from the ItemInserted event of a FormView (.Net Framework 4, Visual Studio 2013 Webforms Application)
Protected Sub PopulateDictionary(myValues As DictionaryEntry())
Dim de As DictionaryEntry
Dim valuesString As String = String.Empty
Dim myDictionary As New Dictionary(Of String, String)
For Each de In myValues
'This works - the string is populated with key/value pairs
valuesString &= "Key=" & de.Key.ToString() & ", " & _
"Value=" & de.Value.ToString() & "<br/>"
'This doesn't - just get the red circle with an X
myDictionary.Add(de.Key.ToString(), de.Value.ToString())
Next
End Sub
What is going on here? I have restarted Visual Studio with no luck.
odd that this works with the "<br/>". it looks like it's missing the closing quote. (and maybe ToString() is not needed?)
valuesString &= "Key=" & de.Key.ToString() & ", " & _
"Value=" & de.Value.ToString() & "<br/>"
it looks like this:
myDictionary.Add(de.Key.ToString(), de.Value.ToString())
just needs to be:
myDictionary.Add(valuesString)
or (not sure...):
myDictionary.Add(DictionaryEntry())

File.Create not working in asp.net

It might be a little funny but I am facing some stupid issue.
I am using
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
and
Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
when I using this the error is given to me is "Could not find a part of the path "
If am storing the path in a string then its working fine else producing error.
For your reference I am copying my function code snippet.
Please help
Thanks
Public Shared Function LogErrorToLogFile(ByVal ee As Exception, ByVal userFriendlyError As String) As String
Try
Dim path As String = context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))
' check if directory exists
If Not Directory.Exists(path) Then
'Directory.CreateDirectory(path)
Directory.CreateDirectory(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
End If
path = path & DateTime.Today.ToString("dd-MMM-yy") & ".log"
' check if file exist
If Not File.Exists(path) Then
File.Create(path).Dispose()
'File.Create(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))).Dispose()
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
End If
' log the error now
Using writer As StreamWriter = File.AppendText(path)
'Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
writer.WriteLine(HttpUtility.HtmlEncode(vbCr & vbLf & "Log written at : " & DateTime.Now.ToString() & vbCr & vbLf & "Error occured on page : " & context.Current.Request.Url.ToString() & vbCr & vbLf & vbCr & vbLf & "Here is the actual error :" & vbLf & ee.ToString()))
writer.WriteLine("==========================================")
writer.Flush()
writer.Close()
End Using
Return userFriendlyError
Catch
Throw
End Try
End Function
If you change the current lines with the comment-outed lines in your function code snippet, you're logic is changed because when you use Path, there is added a filename [dd-MMM-yy].log to the path-string. but you don't use that addition when you use the ConfigurationManager.AppSettings("LogFilePath1") directly!
I assume that you have not used the folder path with slash (ex: #"C:\FolderName\") and that is the reason you are getting the error.

Web UI control to be passed to a class

Hey all i have this code here:
ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "showNotifier", ";$(function() {showNotifier(3000,'#cf5050','" & msg & "');});", True)
That i am wanting to place inside a class file like so:
Public Class topMsgNotifyer
Public Shared Sub show(ByVal delay As Integer, ByVal colorOfBox As String, ByVal message As String)
Try
ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "showNotifier", ";$(function() {showNotifier(" & delay & ",'" & colorOfBox & "','" & message & "');});", True)
Catch ex As Exception
End Try
End Sub
End Class
And of course it has a problem with Me.Page inside the class file.
I can get the current page name by doing this:
Dim pageName = Path.GetFileName(Request.Path)
How can i correct this when calling that class sub from a asp.net page instead of calling it on the page itself?
You could pass the Page object to your show() method, however, a better approach would be to create a class that is a BasePage class, in which your pages inherit from. In that class, make you show() method. Consequently, every page that inherits this BasePage will have access to that method, and Me.Page will be available.
Passing the Page object:
Public Class topMsgNotifyer
Public Shared Sub show(ByVal delay As Integer, ByVal colorOfBox As String, ByVal message As String, ByVal page as System.Web.UI.Page)
Try
ScriptManager.RegisterClientScriptBlock(page, GetType(String), "showNotifier", ";$(function() {showNotifier(" & delay & ",'" & colorOfBox & "','" & message & "');});", True)
Catch ex As Exception
End Try
End Sub
End Class
call it:
topMsgNotifyer.show(30, "Red", "You did something wrong", Me.Page)
These kind of thing are usualy done in a user control which will have access to the page.
An other option you be to pass the Page variable to the function as a parameter.
Or have your function return a String instead with the script, and then call RegisterClientScriptBlock like you are doing.
Why is people saying not to pass an instance of a page? I see nothing wrong with this:
public static void clientOnLoadScript(System.Web.UI.Page instance, string script, bool addScriptTag = false)
{
string toWrite = "$(window).load(function () { \n" + script + "\n });";
instance.ClientScript.RegisterStartupScript(instance.GetType(),"OnLoad", toWrite,addScriptTag);
}
then just call the function:
clientOnLoadScript(this,"script",true);
This works for me. Good luck.

ASP.NET Replacing Line Break with HTML br not working

Hi
I am trying to submit some information into a database using an ASP.NET multiline textbox.
I have the following code:
Dim noteContent As String = Replace(txtNoteContent.InnerText.ToString(), vbCrLf, "<br />")
Shop.Job.Notes.addNote(Request.QueryString("JobID"), ddlNoteFrom.SelectedValue, ddlNoteTo.SelectedValue, noteContent)
The addNote's function code is:
Public Shared Sub addNote(ByVal JobID As Integer, ByVal NoteFrom As Integer, ByVal NoteTo As Object, ByVal NoteContent As String)
Dim newNote As New Job_Note
newNote.Date = DateTime.Now()
newNote.JobID = JobID
newNote.NoteByStaffID = NoteFrom
If Not NoteTo = Nothing Then
newNote.NoteToStaffID = CInt(NoteTo)
End If
newNote.NoteContent = NoteContent
Try
db.Job_Notes.InsertOnSubmit(newNote)
db.SubmitChanges()
Catch ex As Exception
End Try
End Sub
When it submit's the compiler does not seem to detect that line breaks have been entered into the textbox. I have debugged and stepped through the code, and sure enough, it just ignores the line breaks. If I try and replace another character instead of a line break, it works fine.
It doesn't seem to be anything to do with my function, the LINQ insert or anything like that, it simply just doesn't detect the line breaks. I have tried VbCr, and also chr(13) but they do not work either.
Can someone help me? I have been trying ad searching for over an hour trying to sort this.
Thanks
When you do your replace, you should check for VbCrLf (Windows Line Break), VbLf (Unix Line Break) and VbCr (Mac Line Break). If memory serves correct, the standard newline in a HTML textarea element is "\n" (aka VbLf), so you might just get away with replacing VbCrLf with VbLf in your code, but personally I always check for them all just to be safe.
Example
Dim htmlBreakElement As String = "<br />"
Dim noteContent As String = txtNoteContent.Text _
.Replace(vbCrLf, htmlBreakElement) _
.Replace(vbLf, htmlBreakElement) _
.Replace(vbCr, htmlBreakElement)
Shop.Job.Notes.addNote(Request.QueryString("JobID"), ddlNoteFrom.SelectedValue, ddlNoteTo.SelectedValue, noteContent)

Resources