visuaforce page:
<apex:page sidebar="false" controller="UploadOpportunityScheduleLineItem123">
<apex:form >
<apex:sectionHeader title="Upload data from CSV file"/>
<apex:pagemessages />
<center>
<apex:inputFile value="{!contentFile}" filename="{!nameFile}" />
<apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
<br/> <br/>
</center>
</apex:form>
</apex:page>
apex:
public with sharing class UploadOpportunityScheduleLineItem123{
// Global variables
public string nameFile{get;set;}
Public Id parentId{get;set;}
public Blob contentFile{get;set;}
List<account> lstScheduleToUpdate = new List<account>();
public account objSchedule{get;set;}
//String array for taking csv data by line.
String[] filelines = new String[]{};
//set for storing all id's from csv.
set<String> opptoupload{get;set;}
//Main constructor
public UploadOpportunityScheduleLineItem123()
{
//Initalizing required objects.
objSchedule = new account();
opptoupload = new set<String>();
}
//Method to read file content and check extension and file format.
public Pagereference ReadFile()
{
parentId=Apexpages.currentPage().getParameters().get('ParentId');
//If without selecting csv file you clicked on upload it will give error message.
if(nameFile == null)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'You should select csv file to upload');
ApexPages.addMessage(errormsg);
return null;
}
//Taking file extension.
String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
//Checking if file extension is .csv.
if(extension == 'csv' ||extension == 'CSV')
{
nameFile =blobToString( contentFile,'ISO-8859-1');
//Spliting by new line
filelines = nameFile.split('\n');
//Spliting values by (,) for checking coloumn size
for (Integer i=1;i<filelines.size();i++){
String[] inputconvalues = new String[]{};
inputconvalues = filelines[i].split(',');
account b = new account();
b.name= inputconvalues[0];
b.billingcountry = inputconvalues[1];
b.billingcity = inputconvalues[2];
lstScheduleToUpdate.add(b);
}
//Checking if list is not empty then updating.
if(lstScheduleToUpdate.Size()>0)
{
insert lstScheduleToUpdate;
}
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.info,'Batches File uploaded successfully');
ApexPages.addMessage(errormsg);
return null;
}
//If file is not csv type then it will give error message.
else
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'File type should be csv type');
ApexPages.addMessage(errormsg);
return null;
}
}
public static String blobToString(Blob input, String inCharset){
String hex = EncodingUtil.convertToHex(input);
System.assertEquals(0, hex.length() & 1);
final Integer bytesCount = hex.length() >> 1;
String[] bytes = new String[bytesCount];
for(Integer i = 0; i < bytesCount; ++i)
bytes[i] = hex.mid(i << 1, 2);
return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
}
}
test class :
#IsTest(SeeAllData=true)
private class testexceltoaccount
{
static testmethod void testLoadData() {
StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload1'];
UploadOpportunityScheduleLineItem123 testUpload = new UploadOpportunityScheduleLineItem123();
testUpload.contentFile= testdoc.Body;
testUpload.ReadFile();
}
}
Cant able to cross this section of code in code coverage :
String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
//Checking if file extension is .csv.
if(extension == 'csv' ||extension == 'CSV')
{
I tried many possible to cross code coverage but still it is at that point .Please help me in this regard.
Thanks in advance
When we use apex:inputFile on VF page and upload any file, then name of file is automatically update field into the field specified in filename attribute, but when you are writing test class you only specifying content of file
testUpload.contentFile= testdoc.Body;
You should add name in nameFile global variable manually
testUpload.nameFile= 'test.csv';
#IsTest(SeeAllData=true)
private class testexceltoaccount
{
static testmethod void testLoadData() {
StaticResource testdoc = [Select Id,Body,Name from StaticResource where name ='testMethodCSVUpload1'];
UploadOpportunityScheduleLineItem123 testUpload = new UploadOpportunityScheduleLineItem123();
testUpload.contentFile= testdoc.Body;
testUpload.nameFile= 'test.csv';
testUpload.ReadFile();
}
}
Related
I'm trying to create a pdf using MigraDoc. Here's a list of the libraries that I'm using:
MigraDoc.DocumentObjectModel
MigraDoc.DocumentObjectModel.Tables
MigraDoc.Rendering
It throws me an error on printer.RenderDocument(). Code below
private async Task SavePDF()
{
filePath = emulatorFolderPath + "/Signed/" + _reportInformationViewModel.SelectedClient.Username + "-" + DateTime.Now.ToString("dd_MM_yyyy HH-mm") + ".pdf";
MigraDocRendering.PdfDocumentRenderer printer = new MigraDocRendering.PdfDocumentRenderer
{
Document = document
};
printer.RenderDocument();
printer.PdfDocument.Save(filePath);
}
PS: I don't need to use a private font.
I've resolved by implementing IFontResolver
I've added a folder Fonts that contains Open-Sans font.
I've created a folder Helpers that contains a class called GenericFontResolver:
public class GenericFontResolver : IFontResolver
{
public string DefaultFontName => "OpenSans";
public byte[] GetFont(string faceName)
{
if (faceName.Contains(DefaultFontName))
{
var assembly = typeof(ReportPreviewAndSignatureViewModel).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream($"PDFDemo.Fonts.{faceName}.ttf");
using (var reader = new StreamReader(stream))
{
var bytes = default(byte[]);
using (var ms = new MemoryStream())
{
reader.BaseStream.CopyTo(ms);
bytes = ms.ToArray();
}
return bytes;
}
}
else
return GetFont(DefaultFontName);
}
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
var fontName = string.Empty;
switch (familyName)
{
case "Open Sans":
case "OpenSans":
fontName = "OpenSans";
if (isBold && isItalic)
fontName = $"{fontName}-BoldItalic";
else if (isBold)
fontName = $"{fontName}-Bold";
else if (isItalic)
fontName = $"{fontName}-Italic";
else
fontName = $"{fontName}-Regular";
return new FontResolverInfo(fontName);
default:
break;
}
return null;
}
}
Then, on the constructor of the class that needs the font I've added:
GlobalFontSettings.FontResolver = new GenericFontResolver();
Then, when I'm creating the table you must add:
Style style = document.Styles["Normal"];
style.Font.Name = "OpenSans";
I am saving my records using this code:
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
public string fileName { get; set; }
fileName = Path.Combine(path, "sample.wav");
if (!recorder.IsRecording)
{
recorder.StopRecordingOnSilence = TimeoutSwitch.IsToggled;
//Start recording
var audioRecordTask = await recorder.StartRecording();
BtnDoneRec.IsEnabled = false;
await audioRecordTask;
RecEditor.IsEnabled = true;
BtnDoneRec.IsEnabled = false;
PlayButton.IsEnabled = true;
var filePath = recorder.GetAudioFilePath();
if (filePath != null)
{
var stream = recorder.GetAudioFileStream();
using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
}
}
}
else
{
//stop recording ...
await recorder.StopRecording();
}
I want my record to have a specific name which is labeled with my RecEditor
using (var streamReader = new StreamReader(fileName))
{
File.Move("sample.wav", RecEditor.Text + ".wav");
}
So it will rename "sample.wav" to "RecEditor text.wav" every time I click my save button.
But when I click save, it gives me this record
System.IO.FileNotFoundException: 'Could not find file '/sample.wav'.'
The record is stored in /storage/emulated/0/sample.wav
The sample.wav is created in my device but I don't know why it give me 'Could not find file '/sample.wav'.' error. What am i doing wrong here?
I believe that what you're looking is something like this:
if(File.Exists(fileName))
{
var newFileName = Path.Combine(path, $"{RecEditor.Text}.wav");
File.Move(fileName, newFileName);
}
You don't need to open a new Stream as you are doing. Also, you need to put the full file path not only the file name.
You might want to validate that RecEditor.Text is not empty before using its value for the newfileName
Hope this helps.-
My application actually has mail send / receive functionalities to handle.
While receiving the mail, i am unable to view the image which is an inline image being sent from outlook.
Can some one help me how can i catch the image and make available always.
I have java code like below,
try (InputStream stream = new ByteArrayInputStream(Base64
.getMimeDecoder().decode(mail))) {
MimeMessage message = new MimeMessage(null, stream);
Object messageContent = message.getContent();
if (messageContent instanceof String) {
body = (String) messageContent;
} else if (messageContent instanceof MimeMultipart) {
content = (MimeMultipart) messageContent;
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
String disposition = bodyPart.getDisposition();
if (disposition == null
|| disposition
.equalsIgnoreCase(Part.INLINE)) {
Object object = bodyPart.getContent();
if (object instanceof String) {
body = object.toString();
} else if (object instanceof MimeMultipart) {
MimeMultipart mimeMultipart = (MimeMultipart) object;
String plainBody = null;
String htmlBody = null;
for (int j = 0; j < mimeMultipart.getCount(); j++) {
BodyPart multipartBodyPart = mimeMultipart
.getBodyPart(j);
String multipartDisposition = multipartBodyPart
.getDisposition();
String multipartContentType = multipartBodyPart
.getContentType();
if (multipartDisposition == null
&& multipartContentType != null) {
if (multipartContentType
.contains(MediaType.TEXT_HTML)) {
htmlBody = multipartBodyPart
.getContent().toString();
} else if (multipartContentType
.contains(MediaType.TEXT_PLAIN)) {
plainBody = multipartBodyPart
.getContent().toString();
}
}
}
if (htmlBody != null) {
body = htmlBody;
} else {
body = plainBody;
}
}
}
}
}
Client side i am using CKEditor to handle email body data.
Thanks a lot.
i got a solution from the example shared below
https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
But, this example explains, how to find the image in body and store.
I have also done below to replace src
`
Pattern htmltag = Pattern.compile("]src=\"[^>]>(.?)");
Pattern link = Pattern.compile("src=\"[^>]\">");
String s1 = "";
Matcher tagmatch = htmltag.matcher(s1);
List<String> links = new ArrayList<String>();
while (tagmatch.find()) {
Matcher matcher = link.matcher(tagmatch.group());
matcher.find();
String link1 = matcher.group().replaceFirst("src=\"", "")
.replaceFirst("\">", "")
.replaceFirst("\"[\\s]?target=\"[a-zA-Z_0-9]*", "");
links.add(link1);
s1 = s1.replaceAll(link1, "C:\\//Initiatives_KM\\//image.jpg");
}
`
And on top of this, i gonna do Base64 encoding so that i dont require store in file system.
encodedfileString = Base64.getEncoder().encodeToString(bArray);
With all these i can conclude to say, i got solution for my issue. Thank you.
I have a webpage containing test plans. In test plan there are teat cases and some folders.Now am specifying testplanId and folderId in url for getting the list of testcases.How can I change the url by selecting the folderId.
#RequestMapping(value = "/testplan_view", method = RequestMethod.GET)
public String viewTestPlan(Model model, HttpSession session, #RequestParam(value = "testplanId", required = true) Long testplanId,
#RequestParam(value = "folderId", required = false) Long folderId) {
//changing the folder should redirect to folderId
FlashMsgUtil.INSTANCE.checkFlashMsg(session, model);
EcTestplan testPlan = tpDao.findOne(testplanId);
List<EcTestplanTestcaseMapping> tptcLst = tptcDao.findByTestplanId(testPlan);
List<Object[]> tmLst = tpDao.findProductMetricsByTestplanId(testplanId);
List<TestPlanMetricVo> testPlanMetricLst = BizUtil.INSTANCE.flattenTestPlanMetricsByProduct(tmLst);
Integer totalPassCount = 0;
Integer totalCount = 0;
Integer totalNotRunCount = 0;
for (TestPlanMetricVo tpm : testPlanMetricLst) {
totalPassCount = totalPassCount + tpm.getPassCount();
totalCount = totalCount + tpm.getTotal();
totalNotRunCount = totalNotRunCount + tpm.getNotrunCount();
}
//Get all test cases associated with this test plan
List<EcTestcase>testCaseLst = null;
if (folderId == null) {
testCaseLst=tcDao.findAllTestCasesByTestPlanId(testplanId);
} else {
testCaseLst = tcDao.findAllTestCasesByTestPlanIdAndTestFolderId(testplanId,folderId);
}
if (testCaseLst == null) {
testCaseLst = new ArrayList<>();
}
List<EcUser> activeUsersLst = uDao.findByEnabledOrderByUsernameAsc(Boolean.TRUE);
model.addAttribute("tptcLst", tptcLst);
model.addAttribute("activeUsersLst", activeUsersLst);
model.addAttribute("folderList", getFolderList(testPlan));
model.addAttribute("testPlanMetricLst", testPlanMetricLst);
model.addAttribute("testCaseLst", testCaseLst);
model.addAttribute("testPlan", testPlan);
model.addAttribute("tecaseCnt", totalCount);
model.addAttribute("testPlanPassRate", Math.round((totalPassCount * 100.0) / totalCount));
model.addAttribute("testPlanProgressRate", Math.round(((totalCount - totalNotRunCount) * 100.0) / totalCount));
return "testplan_view";
}
private Map<String, String> getFolderList(EcTestplan testPlan) {
// input: testplan
// output: folder list, folder name should be full path
// step 1: loop through all test cases of the test plan
// step 2: use test case object, get test folder object
// step 3: for folder, get all parent folders and use its name, construct string
//
String delimiter = "\\";
Map<String, String> map = new HashMap<>();
List<EcTestplanTestcaseMapping> testCaseMappings = testPlan.getEcTestplanTestcaseMappingList();
for (EcTestplanTestcaseMapping testCaseMapping : testCaseMappings) {
EcTestcase tc = testCaseMapping.getTestcaseId();
EcTestfolder folder = tc.getFolderId();
String fullpath = "";
List<EcTestfolder> pFolders = folder.getAllParentFolderList();
for (EcTestfolder pfolder : pFolders) {
String pfoldername = pfolder.getName();
fullpath += pfoldername + delimiter;
}
fullpath += folder.getName();
map.put(String.valueOf(folder.getId()), fullpath);
}
return map;
}
My Put method is as follows:
public void Post([FromBody]RavenUserView view)
{
if (ModelState.IsValid)
{
var request = new CreateUserRequest();
request.ID = view.ID;
request.Name = view.Name;
request.UserName = view.UserName;
request.Password = EncryptionDecryption.EncryptString(view.Password);//Encrypt The Password
request.Email = view.Email;
request.Phone = view.Phone;
request.Country = "x";
request.Note = "y";
request.IsActive = view.IsActive;
request.Creator = view.Creator;
request.CreationDate = DateTime.UtcNow;
request.ModificationDate = DateTime.UtcNow;
request.Remarks = "z";
var response = _facade.CreateUser(request);
SaveUserDetailsToCookie(response.RavenUser.ID, response.RavenUser.UserName, EncryptionDecryption.DecryptString(response.RavenUser.Password));//Cookie should be stored Decrypted Format
HttpContext.Current.Session[SessionDataKey.UserId.ToString()] = response.RavenUser.ID.ToString();
HttpContext.Current.Session[SessionDataKey.UserName.ToString()] = response.RavenUser.UserName;
}
}
But When I run my project and try to save my information then it throw me an exception "Object Reference is not set to the reference of an object"
I am using Web Api as my controller class.
After reading various documents I found that Api is stateless. Now how can I store my user information for further use.
Use:
public void Post([Bind(Include = "ID,Name,UserName,....")] CreateUserRequest request)
{
if(ModelState.IsValid)
{
var response = _facade.CreateUser(request);
SaveUserDetailsToCookie(response.RavenUser.ID, response.RavenUser.UserName, EncryptionDecryption.DecryptString(response.RavenUser.Password));//Cookie should be stored Decrypted Format
HttpContext.Current.Session[SessionDataKey.UserId.ToString()] = response.RavenUser.ID.ToString();
HttpContext.Current.Session[SessionDataKey.UserName.ToString()] = response.RavenUser.UserName;
}
}