WCF REST upload file - wcf

When server side obtain a zip data package from client side.I unzip this package and parse xml data to sql server.Then return success message to client side!
but I run into problem. I woluld like to return success message to client side in time when client uploaded success but not after inserted into data to database!
Can you help me ?tks in advance! sorry for my bad english!
public IAsyncResult BeginAsyncUpload(string token, Stream data, string fileName, string Org, AsyncCallback callback, object asyncState)
{
if (BaseClass.HasPermission(token))
{
return new CompletedAsyncResult<Stream>(data, fileName,Org);
}
else
{
return null;
}
}
public string EndAsyncUpload(IAsyncResult ar)
{
Stream data = ((CompletedAsyncResult<Stream>)ar).Data;
string fileName = ((CompletedAsyncResult<Stream>)ar).FileName;
string Organization = ((CompletedAsyncResult<Stream>)ar).Org;
try
{
return _streamToFile(data, fileName, Organization);
}
catch
{
return "SUCCESS!";
}
}
THE _streamToFile method insert data into db

First thing is that you can seperate your database insertion code and call that funcation asynchronously.
refer for asynch http://msdn.microsoft.com/en-us/magazine/cc164036.aspx
Second method is, store file in folder A, create seperate win service application to read files from same folder A, extract and insert into sql.Then move to folder B.

Related

Rewriting API from .Net Framework to .netcore ,Getting 'System.NotSupportedException' in attempt to get file stream

I am Migrating one of projects to .NET CORE MVC ,
Previous code had API to Upload document, re-written same
Rewritten Above Code to below code , used "using
Microsoft.AspNetCore.Mvc.WebApiCompatShim" to get HttpRequestMessage
[Older Code: Working Fine in .NET FRAMEWORK]
public HttpResponseMessage UploadFile(string filetype)//old code
{
Stream file = Request.Content.ReadAsStreamAsync().Result;
string id;
id = DocumentHelper.SaveDocument(filetype, file);
return Request.CreateResponse<string>(HttpStatusCode.OK, id);
}
public HttpResponseMessage UploadFile(string filetype)//Re-Written Code
{
HttpRequestMessageFeature requestMessage = new HttpRequestMessageFeature(Request.HttpContext);
HttpRequestMessage httpRequestMessage = requestMessage.HttpRequestMessage;
Stream file = httpRequestMessage.Content.ReadAsStreamAsync().Result;
string id;
id = DocumentHelper.SaveDocument(filetype, file);
return httpRequestMessage.CreateResponse<string>(HttpStatusCode.OK, id);
}
Quickwatch for ReWritten Code when trying to read content
[1]: https://i.stack.imgur.com/cc4AF.png
Tried using Request.Body with stream reader, and enabled buffering.
Any Pointers How to read the stream from Microsoft.AspNetCore.HTTP.HttpRequest,I AM TRYING TO AVOID async function that would force me to change return type

non-invocable member 'File' cannot be used like a method error message- what am I missing?

I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?
This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.

How to use CSV Dataset Config's variable in Bean Shell Post Processor in Jmeter

In my application I have two scenarios.
1. Create: Here we book a hotel room. After booking application returns a transaction ID.
2. Cancel: We need to pass the transaction Id to the application to cancel booking.
I want to test with jmeter in such a way that after a create call is made, the cancel call of the respective create is called with the generated transaction ID automatically.
So I have created two thread groups. One for create where I am calling create API, saving the transaction Id in a CSV file using Regular Expression Extractor & Bean Shell Post Processor. Another thread is for cancel where I am picking the transaction ID using CSV Dataset Config & calling the cancel API.
Problem is I want to delete that transaction ID from CSV file after calling the cancel API. I think Bean Shell Post Processor will do the job. This is my CSV Data Set Config:
Here is my Bean Shell Post Processor code:
File inputFile = new File("/home/demo/LocalFolder/CSV/result.csv");
File tempFile = new File("/home/demo/LocalFolder/CSV/myTempFile.csv");
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = vars.get("transactionId");
//String lineToRemove = "${transactionId}";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println("Completed");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But the transaction ID is not getting deleted from the file. I think that vars.get("transactionId") is not returning anything or returning wrong value. If I hardcode a transation ID then the code works fine. Can anyone help me?
JMeter Variables are local to the current Thread Group only, in order to pass the data between Thread Groups you need to use JMeter Properties (props instead of vars). See Knit One Pearl Two: How to Use Variables in Different Thread Groups article for more detailed explanation and usage example.
P.S. Maybe it would be easier to use HTTP Simple Table Server instead?

RazorEngine Error trying to send email

I have an MVC 4 application that sends out multiple emails. For example, I have an email template for submitting an order, a template for cancelling an order, etc...
I have an Email Service with multiple methods. My controller calls the Send method which looks like this:
public virtual void Send(List<string> recipients, string subject, string template, object data)
{
...
string html = GetContent(template, data);
...
}
The Send method calls GetContent, which is the method causing the problem:
private string GetContent(string template, object data)
{
string path = Path.Combine(BaseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return Engine.Razor.RunCompile(content, "htmlTemplate", null, data);
}
I am receiving the error:
The same key was already used for another template!
In my GetContent method should I add a new parameter for the TemplateKey and use that variable instead of always using htmlTemplate? Then the new order email template could have newOrderKey and CancelOrderKey for the email template being used to cancel an order?
Explanation
This happens because you use the same template key ("htmlTemplate") for multiple different templates.
Note that the way you currently have implemented GetContent you will run into multiple problems:
Even if you use a unique key, for example the template variable, you will trigger the exception when the templates are edited on disk.
Performance: You are reading the template file every time even when the template is already cached.
Solution:
Implement the ITemplateManager interface to manage your templates:
public class MyTemplateManager : ITemplateManager
{
private readonly string baseTemplatePath;
public MyTemplateManager(string basePath) {
baseTemplatePath = basePath;
}
public ITemplateSource Resolve(ITemplateKey key)
{
string template = key.Name;
string path = Path.Combine(baseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return new LoadedTemplateSource(content, path);
}
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context)
{
return new NameOnlyTemplateKey(name, resolveType, context);
}
public void AddDynamic(ITemplateKey key, ITemplateSource source)
{
throw new NotImplementedException("dynamic templates are not supported!");
}
}
Setup on startup:
var config = new TemplateServiceConfiguration();
config.Debug = true;
config.TemplateManager = new MyTemplateManager(BaseTemplatePath);
Engine.Razor = RazorEngineService.Create(config);
And use it:
// You don't really need this method anymore.
private string GetContent(string template, object data)
{
return Engine.Razor.RunCompile(template, null, data);
}
RazorEngine will now fix all the problems mentioned above internally. Notice how it is perfectly fine to use the name of the template as key, if in your scenario the name is all you need to identify a template (otherwise you cannot use NameOnlyTemplateKey and need to provide your own implementation).
Hope this helps.
(Disclaimer: Contributor of RazorEngine)

How to save a byte array to a file from silverlight

I have a SL 3 application connected to a WCF service. This service retrieves an array of bytes. I'd like to save that array as a pdf file using FileStream. The problem is that when the byte array is retrived, I get an exception when trying to show the SaveFileDialog because that action is initiated by the callback method and not from a user action, it seems.
I'd like to know if there is any workaround for this. I already have the byte array, now I need to save it to a location specified by the user. No matter how...
Any clue?
Thanks in advance.
Are you wiring to the method completed event of your async method call? See this
http://www.silverlightshow.net/items/Using-the-SaveFileDialog-in-Silverlight-3.aspx
Inside your call back method, you can implement the logic for writing to a file - first by opening the dialog, and then by getting the pointer to the file stream as shown below.
try
{
byte[] fileBytes = //your bytes here
SaveFileDialog dialog=new SaveFileDialog();
//Show the dialog
bool? dialogResult = this.dialog.ShowDialog();
if (dialogResult!=true) return;
//Get the file stream
using ( Stream fs = ( Stream )this.dialog.OpenFile() )
{
fs.Write( fileBytes, 0, fileBytes.Length );
fs.Close();
//File successfully saved
}
}
catch ( Exception ex )
{
//inspect ex.Message
}