Netsuite webservices in C# - c#

I am working on C# program to upload image file to netsuite. Can anybody help me how to invoke netsuite script(written in
java script) in C# because I can find upload api only in netsuite script. Is there any webservices or functions
in netsuite to upload image file in netsuite ?

You can upload a file directly with SuiteTalk. Examples below are written in C#.
Call the below methods like this:
uploadFile(#"SERIAL_NUMBERS.csv", "csv", "123456");
Methods:
public static void UploadFile(string filename, string filetype, string folderId)
{
var sFileName = filename;
var sNsFileName = filename;
var sFileType = filetype;
var sFolderId = folderId;
var uploadFile = new com.netsuite.webservices.File { attachFromSpecified = true, attachFrom = FileAttachFrom._computer };
if (sFolderId != null)
{
var folderRef = new RecordRef { internalId = sFolderId };
uploadFile.folder = folderRef;
}
// Specify the NetSuite filename
if (sNsFileName != null)
uploadFile.name = sNsFileName;
uploadFile.fileTypeSpecified = true;
if (sFileType != null)
{
if (sFileType.Trim().ToLower().Equals("plaintext"))
uploadFile.fileType = MediaType._PLAINTEXT;
else if (sFileType.Trim().ToLower().Equals("image"))
uploadFile.fileType = MediaType._IMAGE;
else if (sFileType.Trim().ToLower().Equals("csv"))
uploadFile.fileType = MediaType._CSV;
else
uploadFile.fileType = MediaType._PLAINTEXT;
}
else
uploadFile.fileType = MediaType._PLAINTEXT;
uploadFile.content = LoadFile(sFileName);
// Invoke add() operation to upload the file to NetSuite
var response = Service.add(uploadFile);
// Process the response
if (response.status.isSuccess)
{
Console.WriteLine(
"\nThe file was uploaded successfully:" +
"\nFile Record key=" + ((RecordRef)response.baseRef).internalId +
"\nRenaming file");
}
else
{
Console.WriteLine("The file was not uploaded. Please notify the NetSuite team of the following error:");
DisplayError(response.status.statusDetail);
}
}
private static byte[] LoadFile(String sFileName)
{
byte[] data;
try
{
FileStream inFile;
using (inFile = new FileStream(sFileName, FileMode.Open, FileAccess.Read))
{
data = new Byte[inFile.Length];
inFile.Read(data, 0, (int)inFile.Length);
}
}
catch (Exception ex)
{
// Error creating stream or reading from it.
Console.WriteLine(ex.Message);
return null;
}
return data;
}

Related

Create Folder Directory to Save file using xamarin plugin extension

I want to create a folder directory and in that folder, I want to save the image and get the response. but when I check manually using file explorer the folder is not showing.
//take picture code
string DirName = "Sample";
string ImgName = "image.jpg";
string basepath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures);
takePhoto.Clicked += async (sender, args) =>
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
});
byte[] imageArray = null;
if (file != null)
{
using (MemoryStream ms = new MemoryStream())
{
var stream = file.GetStream();
stream.CopyTo(ms);
imageArray = ms.ToArray();
}
}
Stream data = new MemoryStream(imageArray);
if (file == null)
return;
filePath = file.Path;
paths.Enqueue(filePath);
var result = await CrossEDFSTemplate.Current.SaveFile(basepath, DirName,ImgName, filePath);
await DisplayAlert("Succesful", result.ToString(), "ok");
//Directory create code
public async Task<SaveFileResponse> SaveFile(string FolderBasePath, string FolderName, string
FileName, string FileFullPath = null, Stream data = null)
{
SaveCompletionSource = new TaskCompletionSource<SaveFileResponse>();
if (FolderBasePath != null && FolderName != null)
{
var directoryPath = Path.Combine(FolderBasePath, FolderName);
string NemFilePath = Path.Combine(directoryPath, FileName);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
if (FileFullPath != null)
{
var imageData = File.ReadAllBytes(FileFullPath);
File.WriteAllBytes(NemFilePath, imageData);
}
else if (data != null)
{
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(NemFilePath, FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
else
{
var ResponseSaved = new SaveFileResponse("There are no items to Save", null, FileName);
SaveFileError(this, ResponseSaved);
SaveCompletionSource.TrySetResult(ResponseSaved);
}
}
else
{
return await SaveCompletionSource.Task;
}
return await SaveCompletionSource.Task;
}
according to this code, the directory is creating but when I manually checking that folder using file explorer the folder is not showing.
The path Environment.SpecialFolder.MyPictures you used to save the file is internal storage.
In Internal Storage, you couldn't see the files without root permission.
But you could use the code to check the file exist or not in the internal storage.
if (File.Exists(filepath))
{
}
If you want to view it, you could use adb tool. Please check the way in link.
How to write the username in a local txt file when login success and check on file for next login?

ZIP download is blocking because of organisation policy in asp.net

As am having my ZIP file in the folder and if I click download report button am blocking to download based on my organization policy.
But I need to download this ZIP file from the code how can we achieve this.
The code which I used as below
string[] filenames = Directory.GetFiles(SourceFolder);
ZipFilePath = DestinationFolder + #"\" + ZipFileName;
using (ZipOutputStream s = new
ZipOutputStream(File.Create(ZipFilePath)))
{
s.SetLevel(6);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
if (Path.GetFileName(file).Contains(SubString) || Path.GetFileName(file).Contains("logfile"))
{
ZipEntry entry = new
ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0,
buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
}
s.Finish();
s.Close();
}
string DownloadFileName = ZipFilePath;
DownloadFileName = DownloadFileName.Replace("\\", "~");
RadAjaxManager1.ResponseScripts.Add("setTimeout(function(){ document.location.href = 'DownloadHandler.ashx?FileName=" + DownloadFileName + "'; return false; },300);");
The DownloadHandler.ashx page as below
public void ProcessRequest(HttpContext context)
{
try
{
HttpResponse rspns = context.Response;
string FileToDownload = context.Request.QueryString["FileName"];
string FileName = string.Empty;
if (context.Request.QueryString["Name"] != null)
{
FileName = context.Request.QueryString["Name"];
}
if (FileToDownload!=null)
{
FileToDownload = FileToDownload.Replace("~", "\\");
FileName = System.IO.Path.GetFileName(FileToDownload);
}
else
{
//FileName = Convert.ToString(iTAPSession.UserData);
}
rspns.AppendHeader("content-disposition", "attachment; filename=\"" + FileName.Replace(" ", "%20"));
rspns.TransmitFile(FileToDownload);
rspns.End();
}
catch (Exception e)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
am getting the below exception
Based on your organization's access policies, access to this website or download ( http://xxxxxxx/ITAADemo/DownloadHandler.ashx?FileName=D:~ITAADemo~Files~SuperAdmin~bn4wgrusef1xgmjhqokd2yo2~~TextAnalytics~~zipdownload~Report_2018-Jul-19-11-39-31.zip ) has been blocked because the file type "application/zip" is not allowed.

How to compress image before upload on amzon s3 server using c# .net?

Hello i have done api for image upload on amzon s3 server with web api c#.but i want to before upload image need this image to compress but how can do that i don't know.
This is my api =>
[HttpPost]
[Route("FileUpload")]
public HttpResponseMessage FileUpload()
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
string fname = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName.ToString());
string extension = Path.GetExtension(postedFile.FileName);
Image img = null;
string newFileName = "";
string path = "";
img = Image.FromStream(postedFile.InputStream);
string path = ConfigurationManager.AppSettings["ImageUploadPath"].ToString();
newFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".jpeg";
string filePath = Path.Combine(path, newFileName);
SaveJpg(img, filePath); // here i have call method for the save image in my local system.
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
try
{
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = "abc",
InputStream = postedFile.InputStream, // i need this image compress but how can do
Key = path + newFileName
};
PutObjectResponse response = client.PutObject(putRequest);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
throw new Exception("Check the provided AWS Credentials.");
}
else
{
throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
return Request.CreateResponse(HttpStatusCode.OK, Status);
}
}
}
catch (Exception ex)
{
}
return Request.CreateResponse(HttpStatusCode.OK, "Done");
}
This is my ImageCompress method =>
public static void SaveJpg(Image image, string file_name, long compression = 60)
{
try
{
EncoderParameters encoder_params = new EncoderParameters(1);
encoder_params.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Quality, compression);
ImageCodecInfo image_codec_info =
GetEncoderInfo("image/jpeg");
image.Save(file_name, image_codec_info, encoder_params);
}
catch (Exception ex)
{
}
}
This is my api and i need this image to before upload image compress and then after i want to upload this image so any one idea how can do that please let me know.

Store image to Server using WCF services and Xamarin.Forms

I'm developing an mobile application using Xamarin Forms where in an app send an image to server. For sending image we've used WCF services.
Well below is the code for Xamarin Application
using (var memoryStream = new MemoryStream())
{
pick.GetStream().CopyTo(memoryStream);
pick.Dispose();
byte[] byteImageArray = memoryStream.ToArray();
try
{
var imageStream = new ByteArrayContent(byteImageArray);
var multi = new MultipartContent();
multi.Add(imageStream);
var client = new HttpClient();
var result = client.PostAsync("http://www.test.com/Services/Service.svc/SaveImage", multi).Result;
var json = await result.Content.ReadAsStringAsync();
var strNo = JsonConvert.DeserializeObject<string>(json);
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.Message, "Ok");
}
}
And for WCF services
public string SaveImage(Stream data)
{
byte[] byteImage = ReadFully(data);
//Database logic to insert byte array
}
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
Now with this code image is getting converted successfully and getting stored in database blob.
Issue I'm facing is whenever I convert blob back to image, the image gets corrupted. When I insert image into blob with asp.net application the data length of blob is displayed as 18901 whereas while inserting same image with mobile application data length is 18987.
Please help me to resolve the data length issue, or please guide easier way to store image into data base using WCF and Xamarin forms.
Create an WebAPI called PicturesController for example. You must use PUT verb
/// <summary>
/// Receiving an image across WebAPI
/// </summary>
/// <returns></returns>
[HttpPut]
public HttpResponseMessage Put()
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (Request.Content.IsMimeMultipartContent())
{
try
{
Request.Content.LoadIntoBufferAsync().Wait();
Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(
new MultipartMemoryStreamProvider()).ContinueWith((task) => {
MultipartMemoryStreamProvider provider = task.Result;
foreach (HttpContent content in provider.Contents)
{
Stream stream = content.ReadAsStreamAsync().Result;
Image image = Image.FromStream(stream);
try
{
string filename = string.Format("{0}{1}{2}{3}",
DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
DateTime.Now.Second) + ".jpg";
foreach (var h in content.Headers.ContentDisposition.Parameters)
{
if (h.Name.ToLower() == "filename")
{
filename = h.Value.Replace("\\", "/").Replace("\"", "");
var pos = filename.LastIndexOf("/");
if (pos >= 0)
{
filename = filename.Substring(pos + 1);
}
break;
}
}
string filePath = ConfigurationManager.AppSettings["Pictures"]
.ToString();
string fullPath = Path.Combine(filePath, filename);
EncoderParameters encparams = new EncoderParameters(1);
encparams.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
ImageCodecInfo ici = null;
foreach (ImageCodecInfo codec in ImageCodecInfo
.GetImageEncoders())
{
if (codec.MimeType == "image/jpeg")
{
ici = codec;
break;
}
}
image.JpegOrientation().Save(fullPath, ici, encparams);
}
catch (Exception ex)
{
}
}
});
}
catch (Exception ex)
{
result.StatusCode = HttpStatusCode.InternalServerError;
}
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(
HttpStatusCode.NotAcceptable,
"This request is not properly formatted"));
}
}
In this code I create a temporary file name. If you pass one as header parameter, I use that. I save the image in a folder Pictures and I read this folder from web.config. The file is in jpeg format because usually this is the image format on your device.
When you do that, you have to create a webclient in your Xamarin project.
/// <summary>
/// Uploads the photo.
/// </summary>
/// <returns>The photo.</returns>
/// <param name="photoBytes">Photo bytes.</param>
public async Task<bool> UploadPhoto(byte[] photoBytes, int PropertyId, string fileName)
{
bool rtn = false;
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(photoBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") {
FileName = fileName + ".jpg"
};
content.Add(fileContent);
fileContent.Headers.ContentDisposition.Parameters.Add(
new NameValueHeaderValue("<otherParam>", "<otherParamValue>"));
string url = RestURL() + "Pictures/Put";
try
{
using (var client = new HttpClient())
{
// add an authotization token if you have one
//client.DefaultRequestHeaders.Add("authenticationToken", "yourToken");
await client.PutAsync(url, content);
rtn = true;
}
}
catch (Exception ex)
{
}
return rtn;
}
Remember to include
using System.Net.Http;
using System.Net.Http.Headers;
I'm using this implementation in a lot of apps and it's working perfectly. If you have any suggestion to improve it, tell me please.
Simply changing
var multi = new MultipartContent();
multi.Add(imageStream);
To
StreamContent scontent = new StreamContent(pick.GetStream());
HttpContent hp = scontent;
Resolved the issue. Hope I'm not going wrong anywhere.

How to read excel file data using memory stream?

I want to read Excel file from JSON data which I am sending from ARC, Can anyone help me to sorted out?
public bool ControlAttachment(AttachmentFile file)
{
try
{
if (file != null && file.File != null)
{
string xlsfile = file.File;
string [] xls = {"application/excel","application/vnd.msexcel","xls","xlsx","application/vnd.ms-excel",};
if (xls.ToList().Contains(file.FileType.Trim()))
{
file.FileType = ".xls";
byte[] contents = Convert.FromBase64String(xlsfile);
string LogFilePaths = ConfigurationManager.AppSettings["ExcelMapperPath"];
string fileName = file.FileName.Split('.')[0] + file.FileType;
string LogFile = HttpContext.Current.Server.MapPath(LogFilePaths + file.FileName.Split('.')[0] + file.FileType);
System.IO.File.WriteAllBytes(LogFile, contents);
if (!File.Exists(LogFile))
{
File.Create(LogFile).Dispose();
}
MemoryStream ms = new MemoryStream();
using (var fs = new FileStream(LogFile, FileMode.Open, FileAccess.Write))
{
ms.CopyTo(fs);
ms.Dispose();
}
}
}
return true;
}
catch
{
return false;
}
}

Categories

Resources