I'm trying to create the wcf service which will upload the files like pdf,doc,xls,images but pdf, txt files are uploading and opening properly but when i'm trying to upload the image file then the file is getting uploaded but the image is not visible
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "Upload/{fileName}")]
string Upload(string fileName, Stream fileContents);
using (FileStream fs = new FileStream("my path", FileMode.Create))
{
fileContents.CopyTo(fs);
fileContents.Close();
}
try byte array instead of stream and wrapping the class like this:
public class Input
{
[DataMember]
public string fileName { get; set; }
[DataMember]
public byte[] fileContents { get; set; }
}
then simply write the file on disk like this:
public string Upload(Input input)
{
File.WriteAllBytes(input.fileName, input.fileContents);
return "OK";
}
#mohammad check the below image how i'm trying to upload the image file
how i'm trying to upload the image file
Thanks
Related
Before I used to create a .csv file and store it in a local system where the application is running and then I used to send it to AWS S3 Bucket.
Now I don't want to create any file on the application side. I want to write my data to S3 Bucket as a .csv file directly, Is it possible? If possible please guide me the way I can do this.
There is a way to achieve this, we have to send our data as InputStream
In my case, I did these changes:
[1]I updated my Bean class to Override toString() method as follows
public class Employee{
String Id;
String employeeNo;
String name;
//get and set
#Override
public String toString() {
return "{"+ Id +","+ employeeNo + ","+ name + "}";
}
[2]I took the list of data and converted into List<String[]>
List<Employee> employeeList=//get employee list
List<String[]> csvData = toStringArray(employeeList);
My toStringArray() will return List<String[]>
private List<String[]> toStringArray(List<Employee> employeeList) {
List<String[]> records = new ArrayList<String[]>();
// adding header to csv
records.add(new String[] { "EmployeeId", "EmployeeNo", "Name"});
// add data to csv
Iterator<Employee> emp = employeeList.iterator();
while (emp.hasNext()) {
Employee data = emp.next();
records.add(new String[] { emp.getId(), emp.getEmployeeNo(), emp.getName() });
}
return records;
}
[3] Now I converted this data to String
String strCsvData=writeCsvAsString(csvData);
my writeCsvAsString() method is
public String writeCsvAsString(List<String[]> csvData) {
StringWriter s = new StringWriter();
CSVWriter writer = new CSVWriter(s);
writer.writeAll(csvData);
try {
writer.close();
} catch (IOException e) {
}
String finalString = s.toString();
logger.debug("Actual data:- {}", finalString);
return finalString;
}
Now I converted this String into InputStream and I send this to S3 bucket with contentType metadata "text/csv"
InputStream targetStream = new ByteArrayInputStream(strCsvData.getBytes());
I am new in asp.net core. I tried to send json using postman and catch the data into web api controller
In my Controller
[Produces("application/json")]
[Route("api/[controller]/[action]")]
public class HomeController : Controller
{
[HttpPost]
public Student Save(Student s)
{
return _student.Save(s);
}
}
Student.cs
public class Student
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public double Cgpa { get; set; }
}
By using postman, First i am sending as form data and i could successfully save the data
But when i tried to send using raw, then it did hit the action but i couldn't get the data
Here, i am sending name=test and cgpa=3 but in controller i haven't got the value instead got the default value for name and cgpa.
Note: ID field is auto increment.
I am working on a small project with ASP.NET MVC 4 and .net framework 4.5. I have a class RecReservation to deal with user reservations. A user may make a reservation at first and upload 2-3 files later, the files have to be related to a certain reservation. At first I defined a string type in RecReservation to store file path, it worked, but only one file can be related to a reservation in this way, I need a solution to handle multiple file paths.
So I defined a List<string> _recFilePath in my RecReservation class to store the file paths. Each time a file is uploaded, the path of which should be appended to _recFilePath. The class looks like this:
public class RecReservation
{
[HiddenInput(DisplayValue = false)]
public int RecReservationID { get; set; }
public String ProjectName { get; set; }
[Required]
public string ProjectManager { get; set; }
public String Department { get; set; }
[DataType(DataType.Date)]
public DateTime ReservationDate { get; set; }
public String ReservationTime { get; set; }
[Required]
public string CourseName { get; set; }
[Required]
public string InstructorName { get; set; }
[Required]
public string PhoneNumber { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
private List<string> _recFilePath = new List<string>();
public List<string> RecFilePath
{
get
{ return _recFilePath; }
}
public void AddRecFilePath(string newpath)
{
_recFilePath.Add(newpath);
}
}
In the database, I defined a nvarchar(500) data type for _recFilePath.
In the controller, I defined a pair of RecUpload overloads to deal with file uploads:
public ViewResult RecUpload(int recReservationID)
{
RecReservation recReservation = repository.RecReservations.FirstOrDefault(p => p.RecReservationID == recReservationID);
return View(recReservation);
}
[HttpPost]
public ActionResult RecUpload(HttpPostedFileBase file, RecReservation recReservation)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("~/Files/RecUploads"), fileName);
file.SaveAs(path);
repository.AddFilePathToRec(recReservation, path);
TempData["message"] = string.Format("{0} has been uploaded", fileName);
return RedirectToAction("AdminRecList");
}
This is the implementation of AddFilePathToRec
public void AddFilePathToRec(RecReservation recReservation, string newFilePath)
{
RecReservation dbEntry = context.RecReservations.Find(recReservation.RecReservationID);
if (dbEntry != null)
{
dbEntry.AddRecFilePath(newFilePath);
}
context.SaveChanges();
}
Now that I have tested the implementation, files upload works fine, but no path is added to _recFilePath field in my database. So what is the reason for this? Help is appreciated! Thank you in advance.
I've roughly followed this example but it doesnt solve my Sitecore-related redirect problem.
sitecore web form for marketers form post to external url
I've confirmed that my form POST works properly by using a 3rd party POST test tool. The problem I'm having is that in Sitecore they use a successMode to determine what the user wants todo if the submit is a success. If the user selects successmode/message, the form redirects back to a thank you message. If the user selects successmode/redirect, the success method pipeline looks for the success page value in the form and then a redirect happens to that URL. The problem with the redirect is that it loses my POST data.
Can anyone provide a Sitecore example of how they executed a form POST, and then redirect to the target external URL without losing POST values?
Did you use the successmode settings in the form?
I'm debating whether to overrride the successmode redirect pipeline, add conditions and test but I'm open to a solution that could include jquery.
Here's is my code:
using Sitecore.Data;
using Sitecore.Form.Core.Client.Data.Submit;
using Sitecore.Form.Core.Controls.Data;
using Sitecore.Form.Submit;
using System.Web;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Text;
using Sitecore.Forms.Core.Data;
using Sitecore.Form.Core.Configuration;
using Sitecore.Forms.Core.Crm;
using System;
using System.IO;
using System.Net;
using Sitecore.Diagnostics;
using System.Text;
namespace XXXWffmExternals
{
public class Redirect : ISaveAction
{
UrlString url = new UrlString("https://XXX.XXX/default.asp");
public virtual void Execute(ID formid, AdaptedResultList fields, params object[] data)
{
String strResult = "";
strResult = setPost(url.ToString(), fields);
}
public String setPost(string url, AdaptedResultList fieldListForPOST)
{
String resultReturn = "";
AdaptedControlResult firstname = fieldListForPOST.GetEntry(this.First_Name, "First_Name");
AdaptedControlResult lastname = fieldListForPOST.GetEntry(this.Last_Name, "Last_Name");
AdaptedControlResult billingaddress = fieldListForPOST.GetEntry(this.Billing_Address, "Billing_Address");
AdaptedControlResult billingcity = fieldListForPOST.GetEntry(this.Billing_City, "Billing_City");
AdaptedControlResult billingstate = fieldListForPOST.GetEntry(this.Billing_State, "Billing_State");
AdaptedControlResult billingzip = fieldListForPOST.GetEntry(this.Billing_Zip, "Billing_Zip");
AdaptedControlResult billingphone = fieldListForPOST.GetEntry(this.Billing_Phone, "Billing_Phone");
AdaptedControlResult email = fieldListForPOST.GetEntry(this.Email, "Email");
AdaptedControlResult amount = fieldListForPOST.GetEntry(this.Amount, "Amount");
AdaptedControlResult desc = fieldListForPOST.GetEntry(this.Description, "Description");
AdaptedControlResult login = fieldListForPOST.GetEntry(this.Login, "Login");
AdaptedControlResult acct = fieldListForPOST.GetEntry(this.Account, "Account");
AdaptedControlResult fund = fieldListForPOST.GetEntry(this.Fund, "Fund");
AdaptedControlResult org = fieldListForPOST.GetEntry(this.Org, "Org");
AdaptedControlResult source_code = fieldListForPOST.GetEntry(this.Source_Code, "Source_Code");
String post =
"First_Name=" + firstname.Value +
"&Last_Name=" + lastname.Value +
"&Billing_Address=" + billingaddress.Value +
"&Billing_City=" + billingcity.Value +
"&Billing_State=" + billingstate.Value +
"&Billing_Zip=" + billingzip.Value +
"&Billing_Phone=" + billingphone.Value +
"&Email=" + email.Value +
"&Amount=" + amount.Value +
"&Description=" + desc.Value +
"&Login=" + login.Value +
"&Account=" + acct.Value +
"&Fund=" + fund.Value +
"&Org=" + org.Value +
"&Invoice_Num=" + "DVXXXX";
resultReturn = sendPost(url.ToString(), post);
return resultReturn;
}
public String sendPost(string url, string post)
{
String result = "";
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
// Set credentials to use for this request.
objRequest.Credentials = CredentialCache.DefaultCredentials;
// Convert POST data to a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(post);
// Set the ContentLength property of the WebRequest.
objRequest.ContentLength = byteArray.Length;
// Set the ContentType property of the WebRequest.
objRequest.ContentType = "application/x-www-form-urlencoded";
// Get the request stream.
Stream dataStream = objRequest.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = objRequest.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
result = reader.ReadToEnd ();
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
return result;
}
public string First_Name { get; set; }
public string Last_Name { get; set; }
public string Billing_Address { get; set; }
public string Billing_City { get; set; }
public string Billing_State { get; set; }
public string Billing_Zip { get; set; }
public string Billing_Phone { get; set; }
public string Email { get; set; }
public string Amount { get; set; }
public string Description { get; set; }
public string Login { get; set; }
public string Account { get; set; }
public string Fund { get; set; }
public string Org { get; set; }
public string Invoice_Num { get; set; }
public string Source_Code { get; set; }
}
}
Why do you want to use WFFM for the form if you don't want to invoke any of the WFFM functionality? The point of WFFM is to allow marking people to create their own forms without any Developer input. You're having to edit all the post data in your code which pretty much eliminates the ability for anyone to edit the form without developer input. I'd say, if you're going to go through the process of writing all the code to submit your code by hand, you can use a Sitecore item to create the form and then use your own code for processing. Skip WFFM. It's a lot more work to do things as you suggested than to just manually create a form.
If you really need any WFFM end functionality, you can easily call them... it's still way easier than trying to override WFFM base functionality to inject your own functionality.
I was wondering if anyone had any pointers for parsing json data consumed from a URL in Asp.Net. I've found plenty of docs about Model Binding json datatypes but this is coming from a URL and I cant seem to find an example for that. The closest thing I've found is datacontractjsonserializer but again, I cant seem to find an example of that in context with a URL outputting the json data. Any help is appreciated.
You could use the JavaScriptSerializer class. You start by defining a model class which will hold the data. So let's suppose that the remote URL returns the following JSON:
{ name: 'John', addresses: [ { city: 'Paris' }, { city: 'London' } ] }
which could be represented by this model:
public class Person
{
public string Name { get; set; }
public Address[] Addresses { get; set; }
}
public class Address
{
public string City { get; set; }
}
And then deserialize the received JSON back to the model:
var serializer = new JavaScriptSerializer();
// TODO: Fetch the JSON from a remote URL
var json = "{name: 'foo', addresses: [{city: 'Paris'}, {city: 'London'}]}";
var person = serializer.Deserialize<Person>(json);
UPDATE:
In order to fetch the JSON from remote url you could use WebClient:
using (var client = new WebClient())
{
string json = client.DownloadString("http://someurl.com");
}
Here is what I have so far. A product of all answers that I get here in stack.
The idea is to get the json value from external web service and publish it in my controller as a json values and I dont have to create model for it. Hope this helps.
public class ApiJson: Controller
{
public JsonResult getUser()
{
WebClient client = WebClient();
NameValueCollection data = new NameValueCollection();
data.Add("param1", "value1");
byte[] result = client.UploadValues("http://localhost:9000/", data);
String json = Encoding.ASCII.GetString(result);
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(json);
return Json(item, JsonRequestBehavior.AllowGet);
}
}