I got an old Windows Forms Tool that I wrote a few years ago, which is using WebBrowser. I want to change it to WebView2 so it's more compatible with new Browsers, as it won't work anymore if you have like Edge Browser installed.
Here is my original Code which works:
public void SubmitData(string link = "")
{
WebBrowser wb = new WebBrowser();
try
{
if(link != "")
{
wb.Navigate(link, "_Blank");
}
else
{
String postdata = "portfolio=" + ControlHelper.SerializeXMLString(pf);
System.Text.Encoding encod = System.Text.Encoding.UTF8;
byte[] bytVal = encod.GetBytes(postdata);
//navString = "http://lt.morningstar.com/4uzvsjb3c3/xray/default.aspx?" + HttpUtility.UrlEncode(bytVal);
wb.Navigate("http://lt.morningstar.com/4uzvsjb3c3/xray/default.aspx", "_Blank", bytVal, "Content-Type: application/x-www-form-urlencoded");
}
}
catch(Exception ex)
{
FileLogger.HandleError("Submit caused an error!", true, true, "Error (Main, SubmitData): " + ex.Message, GlobalData._TempPath, GlobalData._logfile);
}
finally
{
//use to close app and dispose
wb.Dispose();
}
}
This is the new one, on which I get an error: ("The object reference was not set to an object instance.")
WebView2 wb2 = new WebView2();
String postdata = "portfolio=" + ControlHelper.SerializeXMLString(pf);
System.Text.Encoding encod = System.Text.Encoding.UTF8;
byte[] bytVal = encod.GetBytes(postdata);
navString = "http://lt.morningstar.com/4uzvsjb3c3/xray/default.aspx?" + HttpUtility.UrlEncode(bytVal);
Uri uri = new Uri(navString);
wb2.CoreWebView2.Navigate(navString);
//wb2.Source = uri;
wb2.Show();
I haven't worked with this for quite a while, so I'm not sure what I'm doing wrong here.
I appreciate any help on this.
Related
How can I download the "RDL report files" from SQL Report Server 2008 programatically (vb.net).
I just need to download all reports and upload all back in one click event. Is this possible?
Several times, I have used a program called SSRSExtractor (open source). It is available on CodeProject.com http://www.codeproject.com/Articles/339744/SSRS-Downloading-RDL-Files
I also had some code before to download reports from ssrs server
public void SaveAdhocReportsToFile()
{
string inputPath = "Reports";
string outPutDir = "D:\\Reports\\";
ExportListItemToFiles("/" + inputPath, ".rdl", outPutDir, ItemType.Report);
}
private void ExportListItemToFiles(string inputPath, string fileExtension, string outPutFolder, string itemType)
{
try
{
Console.WriteLine("Exporting " + itemType + " from SSRS - folder " + inputPath + " to " + outPutFolder);
string outPutFile = string.Empty;
List<CatalogItem> items = ReportService.ListChildren(inputPath, false).Where(x => x.TypeName == itemType).ToList();
foreach (CatalogItem item in items)
{
byte[] rpt_def = null;
XmlDocument doc = new XmlDocument();
rpt_def = ReportService.GetItemDefinition(item.Path);
MemoryStream stream = new MemoryStream(rpt_def);
outPutFile = string.Format(#"{0}{1}" + fileExtension, outPutFolder, item.Name);
if (File.Exists(outPutFile))
File.Delete(outPutFile);
doc.Load(stream);
doc.Save(outPutFile);
}
}
catch (SoapException ex)
{
throw new Exception(ex.Message);
}
}
You can refer to ReportingService2010 Methods: https://msdn.microsoft.com/en-us/library/reportservice2010.reportingservice2010_methods%28v=sql.120%29.aspx
This err msg is the next one I get after resolving “NotSupportedException” as noted here
I don't even reach the break point in the server code (set on the first line of the method that should be getting called).
This is the relevant server code:
[Route("api/PlatypusItems/PostArgsAndXMLFileAsStr")]
public async void PostArgsAndXMLFileAsStr([FromBody] string stringifiedXML, string serialNum, string siteNum)
{
string beginningInvoiceNum = string.Empty; // <= Breakpoint on this line
string endingInvoiceNum = string.Empty;
XDocument doc = XDocument.Load(await Request.Content.ReadAsStreamAsync());
. . .
And the client (handheld, Compact Framework) code:
private void menuItem4_Click(object sender, EventArgs e)
{
GetAndSendXMLFiles("LocateNLaunch"); // There is a "LocateNLaunch.xml" file
}
private void GetAndSendXMLFiles(string fileType)
{
string serNum = User.getSerialNo();
string siteNum = User.getSiteNo();
if (serNum.Length == 0)
{
serNum = "8675309";
}
if (siteNum.Length == 0)
{
siteNum = "03";
}
string uri = string.Format("http://localhost:28642/api/PlatypusItems/PostArgsAndXMLFileAsStr?serialNum={0}&siteNum={1}", serNum, siteNum);
List<String> XMLFiles = HHSUtils.GetXMLFiles(fileType, #"\");
MessageBox.Show(XMLFiles.Count.ToString());
foreach (string fullXMLFilePath in XMLFiles)
{
MessageBox.Show(fullXMLFilePath);
RESTfulMethods.SendXMLFile(fullXMLFilePath, uri, 500);
}
}
public static string SendXMLFile(string xmlFilepath, string uri, int timeout) // timeout should be 500
{
MessageBox.Show(string.Format("In SendXMLFile() - xmlFilepath == {0}", xmlFilepath));
MessageBox.Show(string.Format("In SendXMLFile() - uri == {0}", uri));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/xml";
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("SendXMLFile exception " + ex.Message);
request.Abort();
return string.Empty;
}
}
}
Running this code, I see from the client the following "debug strings":
0) "1" (from MessageBox.Show(XMLFiles.Count.ToString());)
1) "\Program Files\LocateNLaunch\LocateNLaunch.xml" (from MessageBox.Show(fullXMLFilePath);)
2) "In SendXMLFile() - xmlFilePath == \Program Files\LocateNLaunch\LocateNLaunch.xml" (from MessageBox.Show(string.Format("In SendXMLFile() - xmlFilepath == {0}", xmlFilepath));)
3) "In SendXMLFile() - uri == http://localhost:28642/api/PlatypusItems/PostArgsAndXMLFileAsStr?serialNum=8675309&siteNum=03" (from MessageBox.Show(string.Format("In SendXMLFile() - uri == {0}", uri));)
- and then this one from somewhere:
4) "SendXMLFile exception Unable to connect to the remote server"...
So what could be causing this inability to connect?
UPDATE
The same thing ("Unable to Connect to the Remote Server") happens with this code (different operation, but also from the WindowsCE/Compact Framework/handheld app that tries to connect to the Web API server app):
private void menuItem3_Click(object sender, EventArgs e)
{
string serNum = User.getSerialNo();
if (serNum.Length == 0)
{
serNum = "8675309";
}
string clientVer =
HHSUtils.GetFileVersion(#"\Application\sscs\vsd_setup.dll");
if (clientVer.Contains("Win32Exception"))
{
clientVer = "0.0.0.0";
}
MessageBox.Show(string.Format("After call to GetFileVersion(), serial num == {0};
clientVer == {1}", serNum, clientVer));
string uri =
string.Format("http://localhost:28642/api/FileTransfer/GetHHSetupUpdate?
serialNum={0}&clientVersion={1}", serNum, clientVer);
RESTfulMethods.DownloadNewerVersionOfHHSetup(uri);
}
public static void DownloadNewerVersionOfHHSetup(string uri)
{
string dateElements = DateTime.Now.ToString("yyyyMMddHHmmssfff",
CultureInfo.InvariantCulture);
var outputFileName = string.Format("HHSetup_{0}.exe", dateElements);
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string statusCode = webResponse.StatusCode.ToString();
if (statusCode == "NoContent")
{
MessageBox.Show("You already have the newest available version.");
}
else
{
var responseStream = webResponse.GetResponseStream();
using (Stream file = File.Create(outputFileName))
{
CopyStream(responseStream, file);
MessageBox.Show(string.Format("New version downloaded to {0}",
outputFileName));
}
}
}
catch (WebException webex)
{
MessageBox.Show("DownloadNewerVersionOfHHSetup: " + webex.Message);
}
}
// I see the "After call to GetFileVersion()" message in menuItem3_Click() handler, but then "DownloadNewerVersionOfHHSetup: Unable to Connect to the Remote Server" in DownloadNewerVersionOfHHSetup()
And yes, the server app is running.
UPDATE 2
Here is the code that I tested prior to "dumbing it down" (retrofitting it, making it as similar as possible to this working test code, yet that may not be saying much) for Compact Framework:
Client code:
DownloadTheFile(textBoxFinalURI.Text); // with textBoxFinalURI.Text being
"http://localhost:28642/api/FileTransfer/GetUpdatedHHSetup?
serialNum=8675309&clientVersion=1.3.3.3" and the file on the server being
version 1.4.0.15
private void DownloadTheFile(string uri)
{
var outputFileName = "Whatever.exe";
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string statusCode = webResponse.StatusCode.ToString();
if (statusCode == "NoContent")
{
MessageBox.Show("You already have the newest available version.");
}
else
{
var responseStream = webResponse.GetResponseStream();
using (Stream file = File.Create(outputFileName))
{
CopyStream(responseStream, file);
MessageBox.Show(string.Format("New version downloaded to {0}",
outputFileName));
}
}
}
catch (WebException webex)
{
MessageBox.Show(webex.Message);
}
}
Server code:
public HttpResponseMessage GetHHSetupUpdate(string serialNum, string clientVersion)
{
HttpResponseMessage result;
string filePath = GetAvailableUpdateForCustomer(serialNum);
FileVersionInfo currentVersion = FileVersionInfo.GetVersionInfo(filePath);
if (!ServerFileIsNewer(clientVersion, currentVersion))
{
result = new HttpResponseMessage(HttpStatusCode.NoContent);
}
else
{
result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(filePath, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
}
return result;
}
private string GetAvailableUpdateForCustomer(string serialNum)
{
if (serialNum == "8675309")
{
return HostingEnvironment.MapPath(#"~\App_Data\HHSetup.exe");
}
else
{
return HostingEnvironment.MapPath(#"~\App_Data\HDP.exe");
}
}
// clientFileVersion is expected to be something like "1.4.0.15"
private bool ServerFileIsNewer(string clientFileVersion, FileVersionInfo serverFile)
{
Version client = new Version(clientFileVersion);
Version server = new Version(string.Format("{0}.{1}.{2}.{3}",
serverFile.FileMajorPart, serverFile.FileMinorPart,
serverFile.FileBuildPart, serverFile.FilePrivatePart));
return server > client;
}
... This code works fine (server code is the same; the client code has been "retrofied")
I can't use the code as-is because of the limitations of Compact Framework / Windows CE. As the title of this post makes clear, I'm not even able to connect to the server from there yet. Is it possible? If so, what needs to change in my client code (not the client code in Update 2, which works in newer versions of .NET, but the client code shown prior to there)?
It's a similar story with the other method that is also returning "Unable to connect to the remote server" - it works fine in "modern" code running in a test app, but once it's retrofitted (better word than refactored when "dumbing down" to Compact Frameworkerize the code).
UPDATE 3
I tried to get more info from the err msg with the code below (old line commented out), but this "rewards" me instead with a NullReferenceException:
catch (WebException webex)
{
//MessageBox.Show("DownloadNewerVersionOfHHSetup: " + webex.Message);
string msg = webex.Message;
string innerEx = webex.InnerException.ToString();
string resp = webex.Response.ToString();
string stackTrace = webex.StackTrace;
string status = webex.Status.ToString();
MessageBox.Show(
string.Format("Message: {0}; Inner Exception: {1}; Response: {2}; Stack Trace: {3}; Status: {4}", msg, innerEx, resp, stackTrace, status));
}
UPDATE 4
As I continued to get NREs, I commented out each subsequent line, one-by-one, until I now have this that runs:
//string innerEx = webex.InnerException.ToString();
//string resp = webex.Response.ToString();
//string stackTrace = webex.StackTrace;
string status = webex.Status.ToString();
MessageBox.Show(
//string.Format("Message: {0}; Inner Exception: {1}; Response: {2}; Stack Trace: {3}; Status: {4}", msg, innerEx, resp, stackTrace, status));
//string.Format("Message: {0}; Response: {1}; Stack Trace: {2}; Status: {3}", msg, resp, stackTrace, status));
//string.Format("Message: {0}; Stack Trace: {1}; Status: {2}", msg, stackTrace, status));
string.Format("Message: {0}; Status: {1}", msg, status));
...but all I get from it is Status of "ConnectFailure" (I already knew that).
UPDATE 5
This runs without an NRE:
string msg = webex.Message;
string innerEx = webex.InnerException.ToString();
string status = webex.Status.ToString();
MessageBox.Show(string.Format("Message: {0}; Status: {1}; inner Ex: {2}", msg, status, innerEx));
And this is what I see:
So why would the server actively refuse the connection?
BTW, ASAP I'm going to bountify this question, or will bountify the answerer after the fact*, with a bounty that would make even Long John Silver and Perro-Negro's eyes glimmer and gleam (cared they for geekCoin, that is).
For facts leading to the arrest and eviction of this bug.
PSYCHE! I changed my mind/there's been a mutiny on the bounty => the bountification will happen here instead.
UPDATE 6
This also (using the "raw" IP Address of the server machine) gives me an NRE:
string uri = string.Format("http://192.168.125.50:28642/api/FileTransfer/GetHHSetupUpdate?serialNum={0}&clientVersion={1}", serNum, clientVer);
...as does using the "friendly name" ("Platypus") of the machine in place of the IP Address.
The large problem I see here is the fact that you have localhost as your address. That's absolutely wrong. localhost means, effectively, "on the same machine as I am running" so unless you've somehow managed to get a async .NET 4.0 web service to run on your Windows CE device and your server code is running there, then this is most certainly not what you want.
If you're running on an emulator, it's still wrong. The emulator is, for all intents and purposes, a separate machine.
You must use the address of the server/PC where that web service is running. It must be a routable address, meaning if you're connected over USB then it's probably ppp_peer and not an IP address (well it resolves to a private address, but the name is easier to remember).
I've been trying to convert a SSRS Report to PDF and save to my local drive using the Reporting Web Services. Though I'm able to generate the corresponding pdf file but the contents of the file are missing. I've checked that the report I'm trying to convert is not an empty one. Only the header section is present there within the generated pdf files. Below is the code I'm using:
protected void GeneratePDFFromReport(object sender, EventArgs e)
{
RS2005.ReportingService2005 rs;
RE2005.ReportExecutionService rsExec;
// Create a new proxy to the web service
rs = new RS2005.ReportingService2005();
rsExec = new RE2005.ReportExecutionService();
// Authenticate to the Web service using Windows credentials
rs.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
rsExec.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
//rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://servername/reportserver/reportservice2005.asmx";
rsExec.Url = "http://servername/reportserver/reportexecution2005.asmx";
string historyID = null;
string deviceInfo = null;
string format = "PDF";
Byte[] results;
string encoding = String.Empty;
string mimeType = "application/pdf";
string extension = String.Empty;
RE2005.Warning[] warnings = null;
string[] streamIDs = null;
// Path of the Report - XLS, PDF etc.
string fileName = #"C:\Report\MemberReport.pdf";
// Name of the report - Please note this is not the RDL file.
string _reportName = #"/ReportFolder/ReportName";
string _historyID = null;
bool _forRendering = false;
RS2005.ParameterValue[] _values = null;
RS2005.DataSourceCredentials[] _credentials = null;
RS2005.ReportParameter[] _parameters = null;
try
{
_parameters = rs.GetReportParameters(_reportName, _historyID, _forRendering, _values, _credentials);
RE2005.ExecutionInfo ei = rsExec.LoadReport(_reportName, historyID);
results = rsExec.Render(format, deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
try
{
FileStream stream = File.Create(fileName, results.Length);
stream.Write(results, 0, results.Length);
stream.Close();
}
catch { }
results = null;
}
catch (Exception ex)
{
throw ex;
}
}
Any help would highly be appreciated. Thanks.
Assuming that SSRS is working OK using browser, please modify your posted code as shown below:
1) Device info string, please set it as follows:
string deviceInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; //Initial value was null
2) Create Header instance before using web call LoadReport:
ExecutionHeader execHeader = new ExecutionHeader();
RE2005.ExecutionHeaderValue = execHeader;
i'm trying to upload a file to an ftp server, i'm using this code :
Uri uri;
if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
{
rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
return;
}
// Verify that we are currently not snapped, or that we can unsnap to open the picker.
if (ApplicationView.Value == ApplicationViewState.Snapped && !ApplicationView.TryUnsnap())
{
rootPage.NotifyUser("File picker cannot be opened in snapped mode. Please unsnap first.", NotifyType.ErrorMessage);
return;
}
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
StorageFile file = await picker.PickSingleFileAsync();
if (file == null)
{
rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
return;
}
PasswordCredential pw = new PasswordCredential();
pw.Password = "pass";
pw.UserName = "username";
BackgroundUploader uploader = new BackgroundUploader();
uploader.ServerCredential = pw;
uploader.Method = "POST";
uploader.SetRequestHeader("Filename", file.Name);
UploadOperation upload = uploader.CreateUpload(uri, file);
Log(String.Format("Uploading {0} to {1}, {2}", file.Name, uri.AbsoluteUri, upload.Guid));
// Attach progress and completion handlers.
await HandleUploadAsync(upload, true);
but it sends me this exception here :
UploadOperation upload = uploader.CreateUpload(uri, file);
"An exception of type 'System.ArgumentException' occurred in Microsoft.Samples.Networking.BackgroundTransfer.exe but was not handled in user code
WinRT information: 'uri': Uploading content is only supported for 'http' and 'https' schemes."
Your answer is right there in the exception message.
To quote the documentation:
FTP is supported, but only when conducting download operations.
So you can't use BackgroundUploader with FTP.
Public Async Function FTP_Uploader(ftpURL As String, filename As String, username As String, password As String, file as StorageFile) As Task(Of Boolean)
Try
Dim request As WebRequest = WebRequest.Create(ftpURL + "/" + filename)
request.Credentials = New System.Net.NetworkCredential(username.Trim(), password.Trim())
request.Method = "STOR"
Dim buffer As Byte() = ReadFiletoBinary(filename, file)
Dim requestStream As Stream = Await request.GetRequestStreamAsync()
Await requestStream.WriteAsync(buffer, 0, buffer.Length)
Await requestStream.FlushAsync()
Return True
Catch ex As Exception
Return False
End Try
End Function
Public Shared Async Function ReadFileToBinary(ByVal filename As String, file As StorageFile) As Task(Of Byte())
Dim readStream As IRandomAccessStream = Await file.OpenAsync(FileAccessMode.Read)
Dim inputStream As IInputStream = readStream.GetInputStreamAt(0)
Dim dataReader As DataReader = New DataReader(inputStream)
Dim numBytesLoaded As UInt64 = Await dataReader.LoadAsync(Convert.ToUInt64(readStream.Size))
Dim i As UInt64
Dim b As Byte
Dim returnvalue(numBytesLoaded) As Byte
While i < numBytesLoaded
inputStream = readStream.GetInputStreamAt(i)
b = dataReader.ReadByte()
returnvalue(i) = b
i = i + 1
End While
readStream.Dispose()
inputStream.Dispose()
dataReader.Dispose()
Return returnvalue
End Function
Had the same issue, this worked for me! :)
I stubled upon the same problem. After a day of work I got it to work with the WebRequest class.
A fully working application with download functionality is available here:
http://code.msdn.microsoft.com/windowsapps/CSWindowsStoreAppFTPDownloa-88a90bd9
I modified this code to enable uploading to the server too.
This is for uploading files:
public async Task UploadFTPFileAsync(Uri destination, StorageFile targetFile)
{
var request = WebRequest.Create(destination);
request.Credentials = Credentials;
request.Method = "STOR";
using (var requestStream = (await request.GetRequestStreamAsync()))
using (var stream = await targetFile.OpenStreamForReadAsync())
{
stream.CopyTo(requestStream);
}
}
And this is for creating directories:
public async Task CreateFTPDirectoryAsync(Uri directory)
{
var request = WebRequest.Create(directory);
request.Credentials = Credentials;
request.Method = "MKD";
using (var response = (await request.GetResponseAsync()))
{
//flush
//using will call the (hidden!) close method, which will finish the request.
}
}
request.Credentials can be filled with NetworkCredential, like this:
private string strFtpAccount;
private string strFtpPassword;
private string strFtpDomain;
public ICredentials Credentials
{
get
{
return new NetworkCredential(strFtpAccount, strFtpPassword, strFtpDomain);
}
}
I have a web reference created from the WSDL, but I'm not allowed to call the function unless I pass in the username / password; the original code for the XML toolkit was:
Set client = CreateObject("MSSOAP.SOAPClient30")
URL = "http://" & host & "/_common/webservices/Trend?wsdl"
client.mssoapinit (URL)
client.ConnectorProperty("WinHTTPAuthScheme") = 1
client.ConnectorProperty("AuthUser") = user
client.ConnectorProperty("AuthPassword") = passwd
On Error GoTo err
Dim result1() As String
result1 = client.getTrendData(expression, startDate, endDate,
limitFromStart, maxRecords
How do I add the AuthUser/AuthPassword to my new code?
New code:
ALCServer.TrendClient tc = new WindowsFormsApplication1.ALCServer.TrendClient();
foreach(string s in tc.getTrendData(textBox2.Text, "5/25/2009", "5/28/2009", false, 500))
textBox1.Text+= s;
Found it: Even if Preauthenticate==True, it doesn't do it. You have to overried the WebRequest:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest request;
request = (HttpWebRequest)base.GetWebRequest(uri);
if (PreAuthenticate)
{
NetworkCredential networkCredentials =
Credentials.GetCredential(uri, "Basic");
if (networkCredentials != null)
{
byte[] credentialBuffer = new UTF8Encoding().GetBytes(
networkCredentials.UserName + ":" +
networkCredentials.Password);
request.Headers["Authorization"] =
"Basic " + Convert.ToBase64String(credentialBuffer);
}
else
{
throw new ApplicationException("No network credentials");
}
}
return request;
}
Since it gets created as a partial class, you can keep the stub in a separate file and rebuilding the Reference.cs won't clobber you.