I have a webpage that when visited, declares a variable called date using the following:
var date=new Date("03 Oct 2013 16:04:19");
That date is then displayed at the top of the page. Is there a way for me to modify that date variable? (and not just the visible HTML source)
I have been experimenting with InvokeScript but am finding it hard to grasp, if anybody knows and could post some examples relating directly to this I'd be hugely grateful. Thankyou.
You can inject any JavaScript code using JavaScript's eval, it works with any IE version. You'd need to make sure the page has at least one <script> tag, but this is easy:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call WebBrowser1.Navigate("http://example.com")
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
'
' use WebBrowser1.Document.InvokeScript to inject script
'
' make sure the page has at least one script element, so eval works
WebBrowser1.Document.Body.AppendChild(WebBrowser1.Document.CreateElement("script"))
WebBrowser1.Document.InvokeScript("eval", New [Object]() {"(function() { window.newDate=new Date('03 Oct 2013 16:04:19'); })()"})
Dim result As String = WebBrowser1.Document.InvokeScript("eval", New [Object]() {"(function() { return window.newDate.toString(); })()"})
MessageBox.Show(result)
End Sub
End Class
Alternatively, you can use VB.NET late binding to call eval directly, instead of Document.InvokeScript, which might be easier to code and read:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call WebBrowser1.Navigate("http://example.com")
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
'
' use VB late binding to call eval directly (seamlessly provided by.NET DLR)
'
Dim htmlDocument = WebBrowser1.Document.DomDocument
Dim htmlWindow = htmlDocument.parentWindow
' make sure the page has at least one script element, so eval works
htmlDocument.body.appendChild(htmlDocument.createElement("script"))
htmlWindow.eval("var anotherDate = new Date('04 Oct 2013 16:04:19').toString()")
MessageBox.Show(htmlWindow.anotherDate)
' the above shows we don't have to use JavaScript anonymous function,
' but it's always a good coding style to do so, to scope the context:
htmlWindow.eval("window.createNewDate = function(){ return new Date().toString(); }")
MessageBox.Show(htmlWindow.eval("window.createNewDate()"))
' we can also mix late binding and InvokeScript
MessageBox.Show(WebBrowser1.Document.InvokeScript("createNewDate"))
End Sub
End Class
According to the documentation, you need to invoke an existing script defined in the client:
JavaScript:
var extDate = new Date("03 Oct 2013 16:04:19");
function test(date) {
alert(date);
extDate = date;
}
You could also call eval and run an anonymous function. This would be the preferred method if you have no control over the page source. Essentially, you would be invoking and running code in the JavaScript interpreter.
C#:
private void InvokeTestMethod(DateTime date)
{
if (webBrowser1.Document != null)
{
webBrowser1.Document.Body.AppendChild(webBrowser1.Document.CreateElement("script"));
webBrowser1.Document.InvokeScript("eval", (Object)"(function() { window.date=new Date('03 Oct 2013 16:04:19'); })()");
webBrowser1.Document.InvokeScript("eval", (Object)"(function() { alert(window.newDate.toString()); })()");
webBrowser1.Document.InvokeScript("eval", (Object)"(function() { window.date=new Date('" + date.ToString("dd MMM yyyy HH:mm:ss") + "'); })()");
webBrowser1.Document.InvokeScript("eval", (Object)"(function() { alert(window.newDate.toString()); })()");
}
}
private void Test()
{
InvokeTestMethod(DateTime.Now);
}
VB.NET
Private Sub InvokeTestMethod([date] As DateTime)
If webBrowser1.Document IsNot Nothing Then
webBrowser1.Document.Body.AppendChild(webBrowser1.Document.CreateElement("script"))
webBrowser1.Document.InvokeScript("eval", new [Object]() {"(function() { window.date=new Date('03 Oct 2013 16:04:19'); })()"}))
webBrowser1.Document.InvokeScript("eval", new [Object]() {"(function() { alert(window.newDate.toString()); })()"}))
webBrowser1.Document.InvokeScript("eval", new [Object]() {"(function() { window.date=new Date('" + [date].ToString("dd MMM yyyy HH:mm:ss") + "'); })()"})
webBrowser1.Document.InvokeScript("eval", new [Object]() {"(function() { alert(window.newDate.toString()); })()"}))
End If
End Sub
Private Sub Test()
InvokeTestMethod(DateTime.Now)
End Sub
http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.invokescript.aspx
By using eval, you can invoke anonymous JavaScript functions and run your own code within the context of the web page. In the last two calls to eval, I set the date using DateTime.Now and format the date in a way that JavaScript can understand.
Related
I cant completly converted the vb.net code to c# code so i decided to make a vb.net dll and then add it to c# form.
But im new about this dll things and i dont know how to acces the objects in C# form. I added C# application to references in dll as i did for the dll too. But i cant still access the timer and 2 labels which are in C# application.
This is my vb.net dll
Public Class Class1
Public Sub Bypass(block1 As String, block2 As String, ok1 As String, ok2 As String)
Try
Dim folderPath As String = Environment.GetFolderPath(SpecialFolder.Windows)
FileSystem.FileClose(New Integer() {1})
FileSystem.FileClose(New Integer() {2})
If My.Computer.FileSystem.FileExists((folderPath & "\xspirit.sys")) Then
FileSystem.FileOpen(1, (folderPath & "\xspirit.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
Else
File.WriteAllBytes((folderPath & "\xspirit.sys"), New Byte() {0})
FileSystem.FileOpen(1, (folderPath & "\xspirit.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
block1 = "Erişim Engellendi"
MsgBox("Erişim Engellendi xspirit")
End If
If My.Computer.FileSystem.FileExists((folderPath & "\xhunter1.sys")) Then
FileSystem.FileOpen(2, (folderPath & "\xhunter1.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
Else
File.WriteAllBytes((folderPath & "\xhunter1.sys"), New Byte() {0})
FileSystem.FileOpen(2, (folderPath & "\xhunter1.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
block2 = "Erişim Engellendi"
MsgBox("Erişim Engellendi xhunter1")
End If
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim ex As Exception = exception1
ProjectData.SetProjectError(ex)
Dim exception As Exception = ex
ProjectData.ClearProjectError()
ProjectData.ClearProjectError()
End Try
Dim p As Process()
p = Process.GetProcessesByName("Wolfteam.bin") 'set wolfteam process
If p.Count = 1 Then ' if wolfteam process detected
ok1 = "XignCode Clear Başarılı"
ok2 = "XignCode Clear Başarılı"
MsgBox("XignCode Clear Başarılı xspirit")
MsgBox("XignCode Clear Başarılı xhunter1")
End If
End Sub
End Class
I tried to convert C# but i cant do it completely so i tried to access the objects from my dll with this code but i couldn't do it (Yes i added it to references).
C#app.Form1(its okay until here but i cant continue this code.It doesn't accept the rest of it)
I wanted to write this actually:
C#app.Form1.Timer1.Enabled = False or C#app.Form1.label1.Text = "test"
I tried too:
Dim test1 As String="test"
'then acces them from C# and then:
vbnetdll.Class1 tt = new vbnetdll.Class1();
label1.Text=f.vbmethod.test1;
But i couldn't do this to. Because it doesn't accept. What is wrong?
By default when you add an item to a form it is declared as a private field in the form's class, like this:
private System.Windows.Forms.Label label1;
So it's not going to accessible from another assembly that references the form. It actually has nothing to do with C# vs vb.net.
Hey all I am using some UIAutomation code that was written in C#. So I converted it into VB.net so that I could integrate it into my own program I am making.
The code that has the error is this line:
Private Sub LogMessage(message As String)
Dispatcher.BeginInvoke(DispatcherPriority.Normal, New SetMessageCallback(AddressOf DisplayLogMessage), message)
End Sub
The error is on the Dispatcher.BeginInvoke stating Error 1 Reference to a non-shared member requires an object reference..
The code in C# looks like this:
private void LogMessage(string message)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new SetMessageCallback(DisplayLogMessage), message);
}
And has no errors and works just fine.
What am I missing from the VB.net version to make it work correctly?
The original C# code can be found HERE.
My converted C# to VB.net code looks like this:
Imports System.Threading
Imports Automation = System.Windows.Automation
Imports System.Windows.Automation
Imports System.Windows.Threading
Public Class Form1
Public Delegate Sub SetMessageCallback(ByVal [_Msg] As String)
Private Sub Automate()
LogMessage("Getting RootElement...")
Dim rootElement As AutomationElement = AutomationElement.RootElement
If rootElement IsNot Nothing Then
LogMessage("OK." + Environment.NewLine)
Dim condition As Automation.Condition = New PropertyCondition(AutomationElement.NameProperty, "UI Automation Test Window")
LogMessage("Searching for Test Window...")
Dim appElement As AutomationElement = rootElement.FindFirst(TreeScope.Children, condition)
If appElement IsNot Nothing Then
LogMessage("OK " + Environment.NewLine)
LogMessage("Searching for TextBox A control...")
Dim txtElementA As AutomationElement = GetTextElement(appElement, "txtA")
If txtElementA IsNot Nothing Then
LogMessage("OK " + Environment.NewLine)
LogMessage("Setting TextBox A value...")
Try
Dim valuePatternA As ValuePattern = TryCast(txtElementA.GetCurrentPattern(ValuePattern.Pattern), ValuePattern)
valuePatternA.SetValue("10")
LogMessage("OK " + Environment.NewLine)
Catch
WriteLogError()
End Try
Else
WriteLogError()
End If
LogMessage("Searching for TextBox B control...")
Dim txtElementB As AutomationElement = GetTextElement(appElement, "txtB")
If txtElementA IsNot Nothing Then
LogMessage("OK " + Environment.NewLine)
LogMessage("Setting TextBox B value...")
Try
Dim valuePatternB As ValuePattern = TryCast(txtElementB.GetCurrentPattern(ValuePattern.Pattern), ValuePattern)
valuePatternB.SetValue("5")
LogMessage("OK " + Environment.NewLine)
Catch
WriteLogError()
End Try
Else
WriteLogError()
End If
Else
WriteLogError()
End If
End If
End Sub
Private Function GetTextElement(parentElement As AutomationElement, value As String) As AutomationElement
Dim condition As Automation.Condition = New PropertyCondition(AutomationElement.AutomationIdProperty, value)
Dim txtElement As AutomationElement = parentElement.FindFirst(TreeScope.Descendants, condition)
Return txtElement
End Function
Private Sub DisplayLogMessage(message As String)
TextBox1.Text += message
End Sub
Private Sub LogMessage(message As String)
Me.Dispatcher.BeginInvoke(DispatcherPriority.Normal, New SetMessageCallback(AddressOf DisplayLogMessage), message)
End Sub
Private Sub WriteLogError()
LogMessage("ERROR." + Environment.NewLine)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim automateThread As New Thread(New ThreadStart(AddressOf Automate))
automateThread.Start()
End Sub
End Class
Found the correct way of doing it:
Private Sub LogMessage(message As String)
Me.BeginInvoke(New SetMessageCallback(AddressOf DisplayLogMessage), message)
End Sub
Thanks goes to #HansPassant for the help.
Dispatcher can be static. I think you need Me.Dispatcher.
I have developed in the past in VB.net and I simply can't figure out how to properly call this function and how to get the response so I can display it on a web page response.
I translated the example c# code to VB. Here is my code behind for an aspx page that I wish to use to make the request and then display the response in my page:
Imports OffAmazonPaymentsService
Imports OffAmazonPaymentsService.Model
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write(GetOrderReferenceDetails(???service???, "asdfsadf", "asdfsadf", "asdfasdf"))
End Sub
Private Shared Function GetOrderReferenceDetails(service As IOffAmazonPaymentsService, sellerId As String, amazonOrderReferenceId As String, addressConsentToken As String) As GetOrderReferenceDetailsResponse
' Required parameters
Dim request As New GetOrderReferenceDetailsRequest()
request.SellerId = sellerId
request.AmazonOrderReferenceId = amazonOrderReferenceId
' Optional parameters
request.AddressConsentToken = addressConsentToken
Return service.GetOrderReferenceDetails(request)
End Function
End Class
I don't know how to call that function's first (service) parameter and to then display the contents of the response.
Let me know if my question is not clear enough.
here is the example they gave in c sharp format....
using OffAmazonPaymentsService;
using OffAmazonPaymentsService.Model;
public class GetOrderReferenceDetailsSample
{
/**
* Sample GetOrderReferenceDetails method that takes generic inputs, constructs a request object,
* and make a call to the service.
*/
private static GetOrderReferenceDetailsResponse GetOrderReferenceDetails(
IOffAmazonPaymentsService service,
string sellerId,
string amazonOrderReferenceId,
string addressConsentToken)
{
// Required parameters
GetOrderReferenceDetailsRequest request = new GetOrderReferenceDetailsRequest();
request.SellerId = sellerId;
request.AmazonOrderReferenceId = amazonOrderReferenceId;
// Optional parameters
request.AddressConsentToken = addressConsentToken;
return service.GetOrderReferenceDetails(request);
}
}
Disclaimer: my VB is "rusty" so debug and improve as necessary
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim props As OffAmazonPaymentsServicePropertyCollection = OffAmazonPaymentsServicePropertyCollection.getInstance()
Dim client As New OffAmazonPaymentsServiceClient(props)
Dim result as GetOrderReferenceDetailsResponse = GetAmzOrderRef(client, props, "oref", "token")
End Sub
Private Shared Function GetAmzOrderRef(service As IOffAmazonPaymentsService, props As OffAmazonPaymentsServicePropertyCollection, amazonOrderReferenceId As String, addressConsentToken As String) As GetOrderReferenceDetailsResponse
Dim request as New GetOrderReferenceDetailsRequest()
With request
.SellerId = props.MerchantID
.AmazonOrderReferenceId = amazonOrderReferenceId
.AddressConsentToken = addressConsentToken
End With
Return service.GetOrderReferenceDetails(request)
End Function
Notes:
you should have your config values set (web.config or app.config as necessary), that's where OffAmazonPaymentsServicePropertyCollection.getInstance() will obtain values
the above sample code will fail (as expected) because of dummy values for reference id and token, but that "error" is from the Amazon API (already) - e.g. response error "invalid reference id" or "invalid token" etc....
Hth....
I'm using .net web browser control to open an url in new window through proxy with credentials. I use this code for that:
Public Function AppendHeader(ByRef OriginalHeader As String, ByVal Addition As String) As Boolean
If OriginalHeader <> "" Then
OriginalHeader = OriginalHeader + vbNewLine
End If
OriginalHeader = OriginalHeader + Addition
OriginalHeader.Trim(vbNewLine.ToCharArray)
End Function
Public Function Base64Enc(ByRef s As String) As String
Base64Enc = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(s))
End Function
Public Sub Navigate()
Dim webBrowser As WebBrowser = New WebBrowser()
Dim headers As String = ""
AppendHeader(headers, "Proxy-Authorization: Basic " & Base64Enc("user:pass"))
'AppendHeader(headers, "Authorization: Basic " & Base64Enc("user:pass"))
webBrowser.Navigate("http://stackoverflow.com", Guid.NewGuid().ToString(), Nothing, headers)
End Sub
This code helps to hide Windows Security window at the first time, but if loading web page sends requests to other urls this window shows again and again (you can see it on a screenshot below).
So what can I do to solve this problem?
(I'm using winforms and vb.net, but C# is suitable too)
Give this a try I am unable to test it :)
Private Sub webBrowser_Navigating(ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs)
Dim credentials As New System.Net.NetworkCredential("user", "pwd", "MyDomain")
Dim proxy As New System.Net.WebProxy("127.0.1.2", 80)
If proxy Is Nothing Then
e.Cancel = True
End If
End Sub
Currently i'm developing a software which uses layered architecture using Visual Studio 2008 and C#.
In that system I want to keep all the text messages(that will be shown using message boxes when necessary) in an XML file so that if I update any message I dont have to compile the whole system. How can I accomplish this? What will be the XML file structure? How the messages will be called from C# code? Please be descriptive and give example.
Thanks.
A better choice for your scenario may be a Resource Satellite DLL. This is a separate DLL which contains a set of resoures that are dynamically loaded into your application. This is how many different applications do localization. And most importantly, there are many tools which support this type of feature.
Changing the messages would simply involve changing this DLL. This does result in a compile, but only of the resources and not the system.
http://msdn.microsoft.com/en-us/library/e9zazcx5.aspx
I would create a class that used a .NET DataSet and DataTable to store the ids and messages (and whatever else you need).
That way the class can use the DataSet.WriteXML() and DataSet.ReadXML() to save/load from any filename you specify and you don't have to worry about "hand crafting" the XML format yourself.
This sounded like a handy class to have, so I wrote one up as a "proof of concept":
'*************************************************************************
' Class: MsgFile
' Author: Ron Savage
' Date: 05/14/2009
'
' This class is an example for using an XML file to hold messages to be
' displayed by an application.
'
' Modification History
' Date Init Comment
' 05/14/2009 RS Created.
'*************************************************************************
Imports Microsoft.VisualBasic
Imports System.IO
Public Class MsgFile
'*************************************************************************
' Class Variables
'*************************************************************************
Private MsgFile As String
Private msgData As DataSet
Private msgTable As DataTable
'*************************************************************************
' Sub: New()
' Author: Ron Savage
' Date: 05/14/2009
'
' Creates a new MsgFile from an existing file, or creates an empty one
' with the specified file name.
'*************************************************************************
Sub New(ByVal msg_File As String)
Dim srcFile As New FileInfo(msg_File)
If (srcFile.Exists()) Then
msgData = New DataSet()
Load(msg_File)
Else
NewFile(msg_File)
End If
End Sub
'*************************************************************************
' Sub: NewFile()
' Author: Ron Savage
' Date: 05/14/2009
'
' Creates a new XML message file.
'*************************************************************************
Sub NewFile(ByVal msg_File As String)
Me.MsgFile = msg_File
If (IsNothing(msgData)) Then
msgData = New DataSet("MyAppMessages")
msgTable = New DataTable("Messages")
msgTable.Columns.Add(New DataColumn("Id", GetType(System.Int32), Nothing, MappingType.Attribute))
msgTable.Columns.Add(New DataColumn("Text", GetType(System.String), Nothing, MappingType.Attribute))
msgData.Tables.Add(msgTable)
setMessage(0, "New file created")
End If
Save()
End Sub
'*************************************************************************
' Sub: Load()
' Author: Ron Savage
' Date: 05/14/2009
'
' Loads an existing XML message file into the dataset.
'*************************************************************************
Public Sub Load(ByVal msgFileName As String)
Dim srcFile As FileInfo = Nothing
Me.MsgFile = msgFileName
srcFile = New FileInfo(msgFileName)
msgData.Clear()
If (srcFile.Exists()) Then
msgData.ReadXml(msgFileName)
msgTable = msgData.Tables("Messages")
End If
End Sub
'*************************************************************************
' Sub: Save()
' Author: Ron Savage
' Date: 10/05/2008
'
' This routine saves the DataSet to an XML file.
'*************************************************************************
Public Overridable Sub Save()
If (Not IsNothing(msgData) And Not MsgFile.Equals("")) Then
Dim fileWriter As StreamWriter = New StreamWriter(MsgFile)
msgData.WriteXml(fileWriter)
fileWriter.Close()
End If
End Sub
'*************************************************************************
' Sub: getMessage()
' Author: Ron Savage
' Date: 05/14/2009
'
' This gets the text of the message.
'*************************************************************************
Public Function getMessage(ByVal msgId As String) As String
Dim rowsFound() As System.Data.DataRow
Dim msgText As String = ""
If (Not IsNothing(msgTable)) Then
rowsFound = msgTable.Select("Id = " + msgId.ToString)
If (rowsFound.Length > 0) Then
msgText = rowsFound(0).Item("Text").ToString
End If
End If
Return (msgText)
End Function
'*************************************************************************
' Sub: setMessage()
' Author: Ron Savage
' Date: 05/14/2009
'
' This sets the text of the message.
'*************************************************************************
Public Sub setMessage(ByVal msgId As Integer, ByVal msgText As String)
Dim rowsFound() As System.Data.DataRow
Dim msgRow As System.Data.DataRow
If (Not IsNothing(msgTable)) Then
rowsFound = msgTable.Select("Id = " + msgId.ToString)
If (rowsFound.Length > 0) Then
msgRow = rowsFound(0)
msgRow.Item("Id") = msgId
msgRow.Item("Text") = msgText
Else
msgRow = msgTable.NewRow()
msgRow.Item("Id") = msgId
msgRow.Item("Text") = msgText
msgTable.Rows.Add(msgRow)
End If
End If
Save()
End Sub
End Class
You might want to add your own custom section to your app.config file to store your messages. However this would require you to update the app.config file each time a message changes.
http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx