The URI prefix is not recognized OnDownloadStringCompleted - c#

I've got a problem with simply method whch gets string from asp.net 4 ashx. I'm running below methods from silverlight application which is being hosted by this asp.net application.
private void LoadPlugins()
{
var serviceAddress = _baseAddress
+ "PluginsService.ashx?"
+ DateTime.Now.Ticks;
var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri(serviceAddress));
}
void client_DownloadStringCompleted(
object sender,
DownloadStringCompletedEventArgs e)
{
var plugins = e.Result.Split(
new string[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries);
foreach (var plugin in plugins)
{
AddXap(_baseAddress + plugin);
}
}
PluginsService.ashx.cs:
namespace MefPlugins.Web
{
/// <summary>
/// Summary description for PluginsService
/// </summary>
public class PluginsService : IHttpHandler
{
private const string PluginsFolderName = "Plugins/";
public void ProcessRequest(HttpContext context)
{
//var pluginFolder = new DirectoryInfo(
// HttpContext.Current.Server.MapPath(
// PluginsFolderName));
//var response = new StringBuilder();
//if (pluginFolder.Exists)
//{
// foreach (var xap in pluginFolder.GetFiles("*.xap"))
// {
// response.AppendLine(
// PluginsFolderName + xap.Name);
// }
//}
var response = new StringBuilder();
response.Append("test");
context.Response.ContentType = "text/plain";
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I get an error:
System.Reflection.TargetInvocationException was unhandled by user code
Message=An exception occurred during the operation, making the result invalid. Check InnerException for exception details.
StackTrace:
w System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
w System.Net.DownloadStringCompletedEventArgs.get_Result()
w MefPlugins.MainPage.client_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
w System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
w System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
InnerException: System.Net.WebException
Message=An exception occurred during a WebClient request.
InnerException: System.NotSupportedException
Message=The URI prefix is not recognized.
StackTrace:
w System.Net.WebRequest.Create(Uri requestUri)
w System.Net.WebClient.GetWebRequest(Uri address)
w System.Net.WebClient.DownloadStringAsync(Uri address, Object userToken)
InnerException:
Where could be a bug? this is an example from http://www.galasoft.ch/sl4u/code/chapter20/20.02-Mef/MefPlugins.zip

The reason for the error lies in which project is startup object selected as your startup project.
When your startup project is the MefPlugins projec (a Silverlight Project)t, the project settings indicate that a web page should be dynamically created to host your Silverlight application (right click on project, select Properties and go to the Debug tab).
The problem you runing into has to do with the location that is used as a prefix for the PluginsService.ashx file. The _baseAddress is set by in the main page constructor by the following code:
var xapUri = App.Current.Host.Source;
_baseAddress = xapUri.AbsoluteUri
.Substring(0, xapUri.AbsoluteUri.IndexOf(xapUri.AbsolutePath))
+ "/";
This means that the Uri of the xap file is used to determine the base uri. Now, as the project is using a dynamically generated container page - which is located on your hard drive and started from there - the above code takes the filesystem root is the _baseAddress. Obviously, the code will not find the PluginsService.ashx page, as it is not there.
Additionally, an .ashx file needs some form of http listener that routes the request from a port to your .ashx page. The listener can be a web server like IIS or the development web server, or some listener you implemented yourself.
To solve the problem make the MefPlugins.Web project your startup project and set MefPluginsTestPage.aspx as your startup page. Now _baseAddress should be something simlilar to http://localhost:6584/.
When this base address is now used to find the PluginsService.ashx page, it will result in a correct URI for the resource (http://localhost:6584/PluginsService.ashx in our case).
In general .ashx files are extensions to a web service (IIS, debug web server, or even some own implementation) they are not part of the silverlight client.

I suspect the problem is that the Uri you're passing to DownloadStringAsync is a relative Uri. That is: "file://PluginsService.ashx" is relative to the current directory. You probably want an absolute Uri (i.e. fully-qualified path name) as in "file://C:\projects\test\PluginsService.ashx".

Related

Error: File operation not allowed. Access to route denied

I am working on a project that uses Silverlight, where I want to show PDFS files of a server path, but when I start debugging my code I find the following exception:
where I generate the flow in the following code:
System.Windows.Browser.HtmlElement myFrame = System.Windows.Browser.HtmlPage.Document.GetElementById("_sl_historyFrame");
if (myFrame != null)
{
DirectoryInfo folderPath = new DirectoryInfo(#"\\192.168.1.216\UploadFileMobilePDF\" + transfer.IdTransfer);
foreach (var file in folderPath.EnumerateFiles("*.pdf", SearchOption.AllDirectories))
{
myFrame.SetStyleAttribute("width", "1024");
myFrame.SetStyleAttribute("height", "768");
Uri uri = new Uri(folderPath + file.FullName);
string path = uri.AbsoluteUri.ToString();
myFrame.SetAttribute("src", path);
myFrame.SetStyleAttribute("left", "0");
myFrame.SetStyleAttribute("top", "50");
myFrame.SetStyleAttribute("visibility", "visible");
}
}
The error marks me when instantiating the DirectoryInfo class folderPath = new DirectoryInfo ()
I don't know if silverlight can't have permissions to server addresses
Your application likely doesn't have permission to access the files on the server you're trying to access.
Look into WindowsImpersonationContext for the most likely way around this. https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsimpersonationcontext?view=netframework-4.8
You'll want a class (say, "MyImpersonator") that uses WindowsImpersonationContext to log onto the server using valid credentials. There are too many details to present an entire solution, but using the class (defined elsewhere) to get a single file might look something like this:
using (var impersonator = new MyImpersonator())
{
string name = ConfigurationManager.AppSettings["name"];
string password = ConfigurationManager.AppSettings["pass"];
if (impersonator.LogOnCrossDomain(account, pass))
{
if (File.Exists(filepath))
{
byte[] content = File.ReadAllBytes(filepath);
}
}
}

Unable to get Presigned Object URL Using AWS SDK for .NET

I am currently working with S3 and need to extract an S3 resource which has a timeout for streaming, so that the client cannot use the URL after a specific amount of time.
I have already used some code provided in the documentation for "Presigned Object URL Using AWS SDK for .NET".
The code will provide a temporary URL which can be used to download an S3 resource by anyone...but within a specific time limit.
I have also used the Amazon S3 Explorer for Visual Studio, but it doesn't support URL generation for resources embedded with AWSKMS key.
Also tried deleting the KMS Key for the S3 folder, but that is throwing an error.
If there is a possible link for deleting KMS keys can you also include it in your answers.
//Code Start
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
namespace URLDownload
{
public class Class1
{
private const string bucketName = "some-value";
private const string objectKey = "some-value";
// Specify your bucket region (an example region is shown).
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USEast1;
private static IAmazonS3 s3Client;
public static void Main()
{
s3Client = new AmazonS3Client(bucketRegion);
string urlString = GeneratePreSignedURL();
Console.WriteLine(urlString);
Console.Read();
}
static string GeneratePreSignedURL()
{
string urlString = "";
try
{
//ServerSideEncryptionMethod ssem = new ServerSideEncryptionMethod("AWSKMS");
GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Key = objectKey,
Expires = DateTime.Now.AddMinutes(5),
Verb = 0,
ServerSideEncryptionKeyManagementServiceKeyId = "some-value",
ServerSideEncryptionMethod = ServerSideEncryptionMethod.AWSKMS
};
urlString = s3Client.GetPreSignedURL(request1);
}
catch (AmazonS3Exception e)
{
Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
}
catch (Exception e)
{
Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
}
return urlString;
}
}
}
SignatureDoesNotMatch
The request signature we calculated does not match the signature you provided. Check your key and signing method.
AKIA347A6YXQ3XM4JQ7A
This is the error that I am getting when I am trying to access the generated URL and that is probably because the AWSKMS authentication is having some issue.
I see it's been a couple of years, but did have an answer for this one? One thing that your code snippet seems to be missing is V4 signature flag set to true:
AWSConfigsS3.UseSignatureVersion4 = true;
Sources:
https://aws.amazon.com/blogs/developer/generating-amazon-s3-pre-signed-urls-with-sse-part-1/
https://aws.amazon.com/blogs/developer/generating-amazon-s3-pre-signed-urls-with-sse-kms-part-2/
You also need to make sure you're providing x-amz-server-side-encryption and x-amz-server-side-encryption-aws-kms-key-id headers on your upload request

c# Rotativa issue in production server using user built template pdf generation

i am developing a enterprise app in c# .net. There are many pdf documents generated in the system. I use Rotativa for pdf handling. There is one pdf which uses user created template in the system. System fetches data from the system and replaces the template variables with the dynamic values from server and downloads the pdf. This particular pdf is working fine in my local and development server, but fails in the production server. Will be glad if somebody could help. i have attached the error and the code. please have a look.
public ActionResult GenerateRedemptionLetterGift(int id, int templateId)
{
try
{
int RedTempId = templateId; //Convert.ToInt32(Request.QueryString["templateId"]);
int type = 2;
RedemptionCode RedemptionObj = new RedemptionCode();
RedemptionObj = BlObj.GetRedemptionDetail(id);
return new Rotativa.MVC.ActionAsPdf("ReturnTemplate", new { id, RedTempId, type }) { FileName = "Redemption_Letter_" + RedemptionObj.Id.ToString() + ".pdf" };
}
catch (Exception ex)
{
throw new Exception("Main Method", ex);
}
}
here i call a function ReturnTemplate as ActionAsPdf where all the data is fetched and replaced in the user created template.
public ActionResult ReturnTemplate(int id, int RedTempId, int type)
{
try
{
RedemptionTemplateBO RedTemp = new RedemptionTemplateBO();
RedTemp = BlObj.GetRedemptionTemplateForEdit(RedTempId);
Hashtable TempStrings = new Hashtable();
if (type == 1)
{
TempStrings = GenerateRedemptionHashTable(id);
}
else if (type == 2)
{
TempStrings = GenerateRedemptionHashTableGift(id);
}
StringBuilder builder = new StringBuilder();
builder.Append("<html><head><title>Redemption Letter</title></head><body><style> #font-face {font-family: myFirstFont;src: url(~/fonts/Roboto-Regular.ttf);} p{font-family: 'Roboto', sans-serif;color: #3e3e3e;font-size: 15px;font-weight: 400;margin-bottom: 10px}</style>");
builder.Append(RedTemp.TemplateContent);
builder.Append("</body></html>");
foreach (string key in TempStrings.Keys)
{
builder.Replace("[" + key + "]", (string)TempStrings[key]);
}
return Content(builder.ToString());
}
catch( Exception ex)
{
throw new Exception("Return Template", ex);
}
}
I have checked in the local using a break point, if i am getting the correct data in the string for returning in the second method. Its coming fine.
Its running fine in both local and development server. I am getting the expected pdf.
But when i run it in production. i am running into an error, and it doesnt seem to be hitting the try catch block also.
Server Error in '/' Application.
Error: Failed loading page http://app.com/Redemption/ReturnTemplate/185?RedTempId=3&type=2 (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: RemoteHostClosedError
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Exception: Error: Failed loading page http://app.com/Redemption/ReturnTemplate/185?RedTempId=3&type=2 (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: RemoteHostClosedError
This is the last few stack trace
Rotativa.Core.WkhtmltopdfDriver.Convert(DriverOptions options, String html) +793
Rotativa.MVC.AsPdfResultBase.CallTheDriver(ControllerContext context) +27
Rotativa.MVC.AsPdfResultBase.BuildPdf(ControllerContext context) +203
Rotativa.MVC.AsPdfResultBase.ExecuteResult(ControllerContext context) +27
WkhtmltopdfDriver takes too long to respond from production server.
Could it be due to some outgoing calls in Rotativa server. But still my other pdf generations work fine with rotativa in the production server.
We had a similar but different error: Failed loading page:...HostNotFoundError
Basically, rotativa was trying to resolve the domain name from within the intranet, but this particular network does not allow you to access their own public facing sites using its bound domain name. Switching to .UrlAsAPdf and using the intranet IP address, fixed this.
Also test the PDF view/ page locally first, to see that it is doing what you want.

Opening a document from Imanage in Word 2016

I am attempting to open an Imanage document, in MS Word, within a temporary test application (for debugging) to later copy over into an ActiveX control project. The error that is popping up is:
Exception thrown at 0x7618851A (msvcrt.dll) in w3wp.exe: 0xC0000005: Access >violation reading location 0x09801000.
If there is a handler for this exception, the program may be safely continued.
The error occurs when running the cmd.Execute line and I am unsure as to why I am getting the error.
using IManage;
using IMANEXTLib;
using System;
namespace WebApplication3
{
public partial class WebForm2 : System.Web.UI.Page
{
IManDatabase imanagedatabase;
IManDMS myDMS = new ManDMSClass();
protected void Page_Load(object sender, EventArgs e)
{
openImanageDoc("docNumber", "versionNumber", "server", "database", ReadOnly);
}
public void imanageLogin(string server, string database)
{
try
{
IManSession session = myDMS.Sessions.Add(server);
IManWorkArea oWorkArea = session.WorkArea;
session.TrustedLogin();
foreach (IManDatabase dbase in session.Databases)
{
if (dbase.Name == database)
{
imanagedatabase = dbase;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void openImanageDoc(string docNo, string versionNo, string server, string database, bool isReadOnly = true)
{
IManDocument doc;
try
{
imanageLogin(server, database);
int iDocNo = int.Parse(docNo);
int iVersion = int.Parse(versionNo);
doc = imanagedatabase.GetDocument(iDocNo, iVersion);
openNRTDocument(ref doc, isReadOnly);
imanagedatabase.Session.Logout();
myDMS.Close();
}
catch (Exception Ex)
{
imanagedatabase.Session.Logout();
throw Ex;
}
finally
{
imanagedatabase = null;
myDMS = null;
}
}
public void openNRTDocument(ref IManDocument nrtDocument, Boolean isReadonly)
{
OpenCmd cmd = new OpenCmd();
ContextItems objContextItems = new ContextItems();
objContextItems.Add("NRTDMS", myDMS);
objContextItems.Add("SelectedNRTDocuments", new[] { (NRTDocument)nrtDocument.LatestVersion });
objContextItems.Add("IManExt.OpenCmd.Integration", false);
objContextItems.Add("IManExt.OpenCmd.NoCmdUI", true);
cmd.Initialize(objContextItems);
cmd.Update();
cmd.Execute();
}
}
}
Due to the nature of the error, I am presuming it is a configuration issue rather than a code error although I could be completely wrong as I am very new to programming.
I have found out that w3wp.exe is an IIS worker process created by the app pool but other than that I have no idea what the numeric code represents. Any help or advice is greatly appreciated.
The error is being raised by the OpenCmd instance because it is most likely trying to access resources such as local registry settings. It's not possible to do that in a web application, unless you host your code in a proprietary technology like ActiveX (which is specific to Internet Explorer)
Actually, it is not appropriate for you to use OpenCmd here. Those type of commands (iManage "ICommand" implementations) are intended to be used in regular Windows applications that have either the iManage FileSite or DeskSite client installed. These commands are all part of the so-called Extensibility COM libraries (iManExt.dll, iManExt2.dll, etc) and should not be used in web applications, or at least used with caution as they may inappropriately attempt to access the registry, as you've discovered, or perhaps even display input Win32 dialogs.
For a web app you should instead just limit yourself to the low-level iManage COM library (IManage.dll). This is in fact what iManage themselves do with their own WorkSite Web application
Probably what you should do is replace your openNRTDocument method with something like this:
// create a temporary file on your web server..
var filePath = Path.GetTempFileName();
// fetch a copy of the iManage document and save to the temporary file location
doc.GetCopy(filePath, imGetCopyOptions.imNativeFormat);
In an MVC web application you would then just return a FileContentResult, something like this:
// read entire document as a byte array
var docContent = File.ReadAllBytes(filePath);
// delete temporary copy of file
File.Delete(filePath);
// return byte stream to web client
return File(stream, MediaTypeNames.Application.Octet, fileName);
In a Web Forms application you could do something like this:
// set content disposition as appropriate - here example is for Word DOCX files
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
// write file to HTTP content output stream
Response.WriteFile(filePath);
Response.End();

Webclient causing an invalid operation exception

I'm trying to download a simple xml file and save it to the users local profile. When trying to download (i don't think this has anything to do with the saving location but i'm not 100% sure) i get the following exception on the webclient.
System.InvalidOperationException
My code is as follows;
public void downloadProxy() {
string url = Properties.Settings.Default.url;
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "/netsettings/proxies.xml");
try
{
WebClient GrabFile = new WebClient();
GrabFile.DownloadFile(url, path);
}
catch (WebException webEx)
{
if (webEx.Status == WebExceptionStatus.ConnectFailure)
{
Console.WriteLine("Are you behind a firewall? If so, go through the proxy server.");
}
}
}
If you are on a Windows operating system, use a backslash (not a slash) as folder separator:
\netsettings\proxies.xml

Categories