how to upload photo to sql using json wcf - asp.net

I am creating WCF for an iphone app. i want to know how to upload photo to the sql using json wcf any idea?this is the process how to connect it to the sql?
public class TestService : ITestService
{
[WebInvoke(Method = "POST", UriTemplate = "UploadFile?fileName={fileName}")]
public string UploadFile(string fileName, Stream fileContents)
{
//save file
string absFileName = "";
try
{
absFileName = string.Format("{0}\\FileUpload\\{1}"
, AppDomain.CurrentDomain.BaseDirectory
, Guid.NewGuid().ToString().Substring(0,6) + ".jpg");
// string fld = #"h:\root\home\amrmk185-001\www\publish\WCFService\FileUpload\" + fileName;
//System.IO.File.Create(absFileName);
using (FileStream fs = new FileStream(absFileName, FileMode.Create))
{
fileContents.CopyTo(fs);
fileContents.Close();
}
return "Upload OK";
}
catch(Exception ex)
{
return "FAIL ==> " + ex.Message + " " + absFileName;
}
}

Related

Add Multiple Images as Inline Attachment in Email Message Body

I am trying to add multiple png images as inline attachments to email body. My email body only has the last image. Looks like the memorysteam was overwritten new one. I tried to use AlternateView as this post suggested How to attach multi images in email body in windows application?. But it does not show any image. How to add multiple images attachments? Thanks.
struct Webpage
{
public string Id { get; set; }
public Byte[] Img { get; set; }
public string SiteName { get; set; }
public DateTime CollectTime { get; set; }
}
//
static void SendMultileImgsWEmail(List<Webpage> msg)
{
MailMessage mailMessage = new MailMessage();
SmtpClient client = new SmtpClient(mailserver);
mailMessage.IsBodyHtml = true;
mailMessage.From = new MailAddress(From);
mailMessage.To.Add(new MailAddress(To));
mailMessage.Subject = "xxx";
foreach (Webpage item in msg)
{
byte[] image = item.Img;
Attachment att = new Attachment(new MemoryStream(item.Img), item.SiteName);
att.ContentDisposition.Inline = true;
att.ContentId = item.Id;
att.ContentType.MediaType = "image/png";
mailMessage.Body += "Website Name: " + item.SiteName + Environment.NewLine + Environment.NewLine;
mailMessage.Body += "Screenshot Time: " + item.CollectTime + Environment.NewLine + Environment.NewLine;
mailMessage.Body = String.Format( #"<img src=""cid:{0}"" />", att.ContentId);
mailMessage.Attachments.Add(att);
}
//send message
try
{
client.Send(mailMessage);
}
catch (Exception ex)
{
throw;
}
}

ASMX and ASPX New WebMethods API Function does Not published

I want to add new Function to My API App.
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetListCOA()
{
ProviderBudgetController oProvider = new ProviderBudgetController();
List<BudgetControllerModel> oResult = oProvider.GetDistinctCOA();
return JsonConvert.SerializeObject(oResult);
}
At ASPX File :
[WebMethod()]
public static string GetData()
{
try
{
ProviderBudgetController oProvider = new ProviderBudgetController();
List<BudgetControllerModel> oResult = oProvider.GetDistinctCOA();
return JsonConvert.SerializeObject(oResult);
}
catch (System.Threading.ThreadAbortException)
{
return "Cancelled.";
}
catch (Exception ex)
{
string source = "BudgetReportRevision -> " + MethodBase.GetCurrentMethod().Name;
ProviderLogError.Insert(source, ex.ToString());
return "Error : " + ex.Message;
}
}
but, when I compile my app, the changes does not affected.
I can not see my new methods.

rdlc Report works in local but not on server

I have a report with some datasets, working perfectly in local, but on the server i get the error :
One or more parameters required to run the report have not been specified.
I don't have any parameters on this report, so i don't understand this error... I have this code in controller :
public ActionResult RunReport(int PremiseId)
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath("~/Views/Report/PremisePricing.rdlc");
Premise premise = _db.GetPremise(PremiseId);
ICollection<PremisePricing> premisePricings;
if (premise.PremiseMeters.Count() > 0)
{
premisePricings = premiseMeterPricingToPremisePricing(_db.FindAllPremiseMeteredPricing(premise).ToList());
}
else
{
premisePricings = _db.FindAllPremisePricing(PremiseId).ToList();
}
// Add your data source
List<ReportDataSource> listDS = new List<ReportDataSource>();
ICollection<Premise> premises = new List<Premise>();
premises.Add(premise);
ReportDataSource premiseDS = new ReportDataSource("Premise", premises);
listDS.Add(premiseDS);
ReportDataSource premisePricingDS = new ReportDataSource("PremisePricing", premisePricings);
listDS.Add(premisePricingDS);
ICollection<CompanyProvider> companyProviders = new List<CompanyProvider>();
CompanyProvider companyProvider = _db.GetCompanyProvider();
companyProviders.Add(companyProvider);
ReportDataSource companyProviderDS = new ReportDataSource("CompPro", companyProviders);
listDS.Add(companyProviderDS);
ICollection<CompanyProviderContactManager> companyProviderContactManager = new List<CompanyProviderContactManager>();
if (companyProvider.CompanyProviderContactManager != null)
{
companyProviderContactManager.Add(companyProvider.CompanyProviderContactManager);
}
ReportDataSource companyProviderContactManagerDS = new ReportDataSource("CompProContactManager", companyProviderContactManager);
listDS.Add(companyProviderContactManagerDS);
ICollection<Customer> customer = new List<Customer>();
if (_db.GetPremiseProviderByPremiseId(PremiseId) != null)
{
Customer cust = _db.GetPremiseProviderByPremiseId(PremiseId).Customer;
customer.Add(cust);
}
ReportDataSource customerDS = new ReportDataSource("Customer", customer);
listDS.Add(customerDS);
RenderReport(localReport, listDS, companyProvider.logo);
return View();
}
private void RenderReport(LocalReport localReport, List<ReportDataSource> listDS, byte[] logo)
{
foreach (ReportDataSource ds in listDS)
{
localReport.DataSources.Add(ds);
}
HttpContextBase imageDirectoryPath = HttpContext;
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Write to the outputstream
//Set content-disposition to "attachment" so that user is prompted to take an action
//on the file (open or save)
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=Pricing." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
Any suggestion?

asp.net upload control is not working in ipad

The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?

How to consume image upload data as byte[] using Spring MVC 3

I need write the image data in a particular directory on the server side but I am getting a null for the raw byte[] image upload data that I am trying to send from an html form and jquery ajaxuploader plugin from here.
Following is the snippet from the controller I am using to handle raw bytes of image being uploaded:
#RequestMapping(value = "uploadImage", method = RequestMethod.POST)
public void uploadImage(byte[] uploadData, Writer writer, HttpServletRequest request) throws IOException, JSONException {
//uploadData is turning out to be null
//..
}
#InitBinder
protected void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(byte[].class,
new ByteArrayMultipartFileEditor());
}
I have got the following configured in the spring configuration file for handling uploads:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
I am using Spring MVC 3. Could someone guide me on how to send raw bytes of upload data?
Thanks.
First, if you're form is uploading an image, make sure your content type is "multipart/form-data". You might want to change your RequestMapping as follows:
#RequestMapping(value = "uploadImage", method = RequestMethod.POST, headers={"content-type=multipart/form-data"})
Also, I'd suggest using CommonsMultipartFile to handle the upload. Change your function signature as follows, where "fieldName" is the name of the input field in your form:
public void uploadImage(byte[] uploadData, Writer writer, HttpServletRequest request, #RequestParam("fieldName") CommonsMultipartFile file)
Then you can get the raw bytes as follows:
file.getBytes()
Make sure you include the commons-fileupload dependency for CommonsMultipartFile.
I'm using spring3 + jquery ajaxform and this works like a charm. Hope this helps!
Following is the JavaScript and HTML code I used on the client side that got things working:
JavaScript:
function createUploader(){
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: 'uploadImage',
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
debug: true,
onSubmit: function(id, fileName){
console.log("id - " + id + ", fileName - " + fileName);
},
onComplete: function(id, fileName, responseJSON) {
console.log("responseJSON - " + responseJSON);
}
});
}
window.onload = createUploader;
HTML:
<div id="file-uploader" >
<noscript>
<p>Please enable JavaScript to upload your property location images</p>
</noscript>
</div>
Controller:
#Controller
public class FranchiseeLocationImageController {
private static final Log logger = LogFactory.getLog(FranchiseeLocationImageController.class);
#Autowired
private ServletContext servletContext;
#Autowired
private FranchiseeLocationImageService franchiseeLocationImageService;
#RequestMapping(value = "uploadImage", method = RequestMethod.POST)
public void uploadImage(byte[] qqfile, Writer writer, #RequestParam("qqfile") String img, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException{
FranchiseeLocationImage image = null;
PrintWriter pr = null;
InputStream is = null;
File file = null;
FileOutputStream fos = null;
String filename = request.getHeader("X-File-Name");
String imageId = FilenameUtils.removeExtension(img);
String imageFormat = franchiseeLocationImageService.getImageFormat();
String outputDir = servletContext.getRealPath("") + File.separator + franchiseeLocationImageService.getImagesDirectory() + File.separator;
File baseDirectory = null;
File output = null;
String path = FilenameUtils.removeExtension(img) + "." + imageFormat;
File outputDirectory = null;
HttpSession session = request.getSession();
/*
HttpSession session = request.getSession(false);
if(session == null) {
session = request.getSession();
}
*/
List<String> franchiseeLocationImages = (List<String>) session.getAttribute("franchiseeLocationImages");
if(franchiseeLocationImages == null) {
franchiseeLocationImages = new ArrayList<String>();
}
logger.debug( "filename - " + filename + " | img - " + img + " | img name - " + FilenameUtils.removeExtension(img) + " | img format - " + FilenameUtils.getExtension(img) + " | uploadData - " + qqfile + " | imageFormat - " + imageFormat);
/**
* Reading the image being uploaded and writing it to images/franchiseeLocation folder ["qqfile" is used instead of "X-File-Name" as "X-File-Name" gives encoded HTML name with "%20" for " "]
*/
try {
pr = response.getWriter();
is = request.getInputStream();
/*
baseDirectory = new File(outputDir);
baseDirectory.mkdirs();
file = new File(outputDir, FilenameUtils.removeExtension(img) + "." + imageFormat);
fos = new FileOutputStream(file);
int copiedNum = IOUtils.copy(is, fos);
*/
outputDirectory = new File(outputDir);
outputDirectory.mkdirs();
output = new File(outputDirectory, path);
BufferedImage sourceImage = ImageIO.read(is);
boolean written = ImageIO.write(sourceImage, imageFormat, output);
franchiseeLocationImages.add(img);
session.setAttribute("franchiseeLocationImages", franchiseeLocationImages);
logger.debug("franchiseeLocationImages - " + franchiseeLocationImages);
logger.debug("outputDirectory - " + outputDirectory + " | output - " + output + " | sourceImage - " + sourceImage + " | is - " + is + " | file - " + file + " |fos - " + fos + " | copiedNum - " + "copiedNum" + " | baseDirectory - " + baseDirectory + " | sourceImage - " + sourceImage + " | written - " + written);
/*
image = franchiseeLocationImageService.processProductImage(qqfile, imageId);
JSONObject json = new JSONObject();
json.put("path", image.getPath());
json.put("id", image.getId());
writer.write(json.toString());
*/
pr.print("{success: true}");
} finally {
writer.close();
/*
try {
fos.close();
is.close();
} catch (IOException ignored) {
}
*/
pr.flush();
pr.close();
}
}
#InitBinder
protected void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(byte[].class,
new ByteArrayMultipartFileEditor());
}
private static String html2text(String html) {
return Jsoup.parse(html).text();
}
}

Resources