JUnit Test of Spreadsheet using Apache POI - junit

I am trying to verify a date that is in a spreadsheet created with Apache POI. When I do a System.out.print the Date variable and the cell contents are the same. Why is the test failing?
#Test
public void testSpreadsheetCont() throws Exception {
Date date = new Date();
boolean success = false;
FileInputStream fileInputStream = new FileInputStream("File Location.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheetAt(0);
HSSFRow row1 = worksheet.getRow(2);
HSSFCell cell0 = row1.getCell(0);
System.out.println(cell0.getDateCellValue());
System.out.println(date);
if (cell0.getDateCellValue() == date) {
success = true;
} else {
success = false;
}
Assert.assertTrue(success);
}
I think that the error is how I am formatting the date in the class that generates the spreadsheet. There it is formatted as ("mm/dd/yyyy hh:mm"). But when I format the date variable to ("mm/dd/yyyy hh:mm") and try to compare the two elements it's unsuccessful.
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat("mm/dd/yyyy hh:mm");
if (cell0.getDateCellValue().toString() == ft.format(date)) {
success = true;
} else {
success = false;
}

use following for comparison. Perhaps this may be the reason.
if(cell0.getDateCellValue().compareTo(date)==0){
success = true;
}else{
success = false;
}

No wonder it does not work because you are comparing two Date references - you will always get false there.

Related

Cannot add created label to threads

I tried to write a function in Google Apps Script that creates a new label in Gmail and adds it to threads.
I have two problems:
When I run the function for the first time (archivedLabel not existing yet) I cannot add it to the threads immediately after it is created.
archivedLabel = GmailApp.getUserLabelByName(labelText) at the end of the if statement will still return null and the script crashes.
If I run the script for the second time (label already created) everything works fine.
The new labels only appear in Gmail after the user refreshes the Gmail App in the browser. Is there a way to do this automatically or a method to refresh the labels and messages so I can see the new label in Gmail without manually reloading the page?
function addArchivedLabel(thread){
var labelText = "Backed up";
var archivedLabel = GmailApp.getUserLabelByName(labelText);
//create new archived label if not already existing
if(archivedLabel == null) {
var textColor = "#89d3b2"; // Please set this.
var backgroundColor = "#ffbc6b"; // Please set this.
var userId = "me";
var resource = Gmail.newLabel();
resource.labelListVisibility = "labelShow";
resource.messageListVisibility = "show";
resource.name = labelText;
var labelColor = Gmail.newLabelColor();
labelColor.textColor = textColor;
labelColor.backgroundColor = backgroundColor;
resource.color = labelColor;
Gmail.Users.Labels.create(resource, userId);
archivedLabel = GmailApp.getUserLabelByName(labelText);
}
archivedLabel.addToThread(thread); //add new label to archived emails
}
I just encountered the same problem
For some reason this is working :
function getOrCreateLabel() {
if (!GmailApp.getUserLabelByName(LABEL_NAME)) {
GmailApp.createLabel(LABEL_NAME)
}
console.log(GmailApp.getUserLabelByName(LABEL_NAME)) // not NULL
}
And this is not working as expected:
function getOrCreateLabel() {
if (!GmailApp.getUserLabelByName(LABEL_NAME)) {
Gmail.Users.Labels.create({
"labelListVisibility": "labelHide",
"messageListVisibility": "hide",
"name": LABEL_NAME
}, "me")
}
console.log(GmailApp.getUserLabelByName(LABEL_NAME)) // NULL
}
For the second function,It seems that appsscript cache the response of GmailApp.getUserLabelByName at runtime.
So in my opinion. You will need to create a trigger, here a working exemple:
function addArchivedLabel(thread){
var labelText = "Backed up";
var archivedLabel = GmailApp.getUserLabelByName(labelText);
const thread_id = UserProperties.getProperty("thread")
// Check if come from trigger
if (thread_id) {
// retrieve the thread
thread = GmailApp.getThreadById(thread_id)
// Clean property and trigger
UserProperties.deleteProperty("thread")
ScriptApp.getScriptTriggers().forEach((p) => {
if (p.getHandlerFunction() == "addArchivedLabel") {
ScriptApp.deleteTrigger(p)
}
})
}
//create new archived label if not already existing
if(archivedLabel == null) {
var textColor = "#89d3b2"; // Please set this.
var backgroundColor = "#ffbc6b"; // Please set this.
var userId = "me";
var resource = Gmail.newLabel();
resource.labelListVisibility = "labelShow";
resource.messageListVisibility = "show";
resource.name = labelText;
var labelColor = Gmail.newLabelColor();
labelColor.textColor = textColor;
labelColor.backgroundColor = backgroundColor;
resource.color = labelColor;
Gmail.Users.Labels.create(resource, userId);
UserProperties.setProperty("thread", thread.getId())
ScriptApp.newTrigger("addArchivedLabel").timeBased().everyMinutes(1).create()
return
}
archivedLabel.addToThread(thread); //add new label to archived emails
}
// fixture to simulate get thread
function main() {
const thread = GmailApp.getInboxThreads()
addArchivedLabel(thread[0])
}
Hope it will help

two different hours subtraction Angular 6

I am trying to do how to subtract two different hours that is captured:
Here is TS code
clockingIn() {
var dt = new Date()
this.clockedIn= new Date().getHours()+':'+ new Date().getMinutes()+':'+ new Date().getSeconds();
console.log('clockin', this.clockedIn);
this.disableClockIn = true;
this.disableClockOut = false;
}
clockingOut() {
var dt2 = new Date();
this.clockedOut= new Date().getHours()+':'+ new Date().getMinutes()+':'+ new Date().getSeconds();
console.log('clockout', this.clockedOut);
this.disableClockIn = false;
this.disableClockOut = true;
}
subtraction() {
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
}
//table
test() {
const data = {
dateClock: this.dateobj(),
Job: this.selectedJob,
clockI: this.clockedIn,
clockO: this.clockedOut,
Hoursworked: this.subtraction()
};
this.dataSource.data.push(data);
this.refresh();
console.log(this.dataSource);
}
So this is a clock in and Clock out.
I want these two can calculate (Clock Out - Clock In) to see the difference of two hours in the table that I made. So this way, I can see the diff time between Clock Out and Clock In.
I am assuming your duration will be calculated in subtraction function.
Below changes will get the result :
subtraction() {
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
// I have set to minutes. Change unit as per your requirement by
// referring doc given as reference
var unit = 'm';
return moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"), unit);
}
Moment.js duration

Downloading Attachment from Exchange Server using SSIS package deployed on another Server

I have built an SSIS package which reads CSV from certain folder. But now I need to download same csv from exchange server.Also Outlook is not installed on my machine. Will I be able to download CSV from exchange server and how ? Thanks!
I have used some of the code from the link http://sqlandbilearning.blogspot.com.au/2014/07/download-email-attachment-using-ssis.html but i have added some new code for removing TCP binding error using ServicePointManager as well as added search filter for retrieving specific emails and this code also takes care of multiple attachment from different emails to be saved on file system.
public void Main()
{
string filePath = "";
string fileName = "";
List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
DateTime now = DateTime.Now;
DateTime beginRecievedTime = new DateTime(now.Year, now.Month, now.Day, 7, 55, 0);
DateTime finishRecievedTime = new DateTime(now.Year, now.Month, now.Day, 8, 15, 0);
EmailMessage latestEmail = null;
try
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.UseDefaultCredentials = true;
//service.Credentials = new WebCredentials("username", "password");
service.Url = new Uri("");
// 10 mails per page in DESC order
ItemView view = new ItemView(10);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Scheduled search"));
SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, beginRecievedTime);
searchFilterCollection.Add(greaterthanfilter);
SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, finishRecievedTime);
searchFilterCollection.Add(lessthanfilter);
SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection);
//Find mails
FindItemsResults<Item> fir = service.FindItems(WellKnownFolderName.Inbox, filter, view);
Dictionary<EmailMessage, string> emailsMap = new Dictionary<EmailMessage, string>();
foreach (Item item in fir.Items)
{
item.Load(); //Load the entire message with attachment
EmailMessage email = item as EmailMessage;
if (email != null)
{
if (email.HasAttachments == true && email.Attachments.Count == 1)
{
if (email.Subject.StartsWith("Scheduled search") == true)
{
filePath = Path.Combine(Dts.Variables["User::SourceFolderPath"].Value.ToString()
, email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
email.Attachments[0].Name);
// fileName = email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
// email.Attachments[0].Name.ToString();
emailsMap.Add(email, filePath);
}
}
}
}
if (emailsMap.Count > 0) {
foreach (var item in emailsMap) {
//Save attachment
EmailMessage email = item.Key;
filePath = item.Value;
FileAttachment fileAttachment = email.Attachments[0] as FileAttachment;
fileAttachment.Load(filePath);
string extractPath = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.Attachments[0].Name;
System.IO.Compression.ZipFile.ExtractToDirectory(filePath, extractPath);
fileName = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
email.Attachments[0].Name.ToString();
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
}
// Dts.Variables["User::SourceFileName"].Value = fileName;
Dts.TaskResult = (int)ScriptResults.Success;
}
catch(System.Runtime.InteropServices.COMException ex)
{
if (Dts.Variables.Locked == true)
{
Dts.Variables.Unlock();
}
//An error occurred.
Dts.Events.FireError(0, "Error occured", ex.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}

Auto manage and protect Created\Updated fields with Entity Framework 5

I want so every added\changed record will have a time stamp of creation\change.
But - so it will be easy to embed and easy to manage - automatically.
Overwrite the 'DbContext' class or embed this in the '.tt' file (Codefirst \ DBFirst)
The code assume so you have the fields 'CreatedOn'\'ModifiedOn' inside the POCO.
If you don't have them, or you have only one - the code will work fine.
Be aware! If you use a extension (as this one) so allow you to do batch updates or changes from a stored procedure - this will not work
EDIT:
I found the source of my inspiration - thanks 'Nick' here
public override int SaveChanges()
{
var context = ((IObjectContextAdapter)this).ObjectContext;
var currentTime = DateTime.Now;
var objectStateEntries = from v in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
where v.IsRelationship == false && v.Entity != null
select v;
foreach (var entry in objectStateEntries)
{
var createdOnProp = entry.Entity.GetType().GetProperty("CreatedOn");
if (createdOnProp != null)
{
if (entry.State == EntityState.Added)
{
if (createdOnProp != null)
{
createdOnProp.SetValue(entry.Entity, currentTime);
}
}
else
{
Entry(entry.Entity).Property("CreatedOn").IsModified = false;
}
}
var modifiedOnProp = entry.Entity.GetType().GetProperty("ModifiedOn");
if (modifiedOnProp != null)
{
modifiedOnProp.SetValue(entry.Entity, currentTime);
}
}
return base.SaveChanges();
}

"Error Encountered: Invalid Argument" in handler function

I'm getting this error in my handler function but I've no clue what's causing it. I've copied the code and debugged it in a non-handler function and there was no error.
function _responseToNext(e) {
var app = UiApp.getActiveApplication();
app.getElementById('btnPrev').setEnabled(true);
var current = parseInt(CacheService.getPublicCache().get('currentItem'));
var agendaItems = Utilities.jsonParse(CacheService.getPublicCache().get('agenda'));
agendaItems[current]['notes'] = e.parameter.tAreaNotes;
agendaItems[current]['status'] = e.parameter.lboxStatus;
CacheService.getPublicCache().put('agenda', Utilities.jsonStringify(agendaItems));
current = current + 1;
CacheService.getPublicCache().put('currentItem', current);
fillAgendaDetail(app);
// only enabled 'Next' if there are more items in the agenda
if (current < agendaItems.length-1) {
app.getElementById('btnNext').setEnabled(true);
}
return app;
}
I suppose, the error cause is that the Cache get method returns null during the 1st execution when the cache is empty. The Utilities.jsonParse throws an exception and the cache becomes in any case empty. Try to use the following modified code.
function _responseToNext(e) {
var app = UiApp.getActiveApplication();
app.getElementById('btnPrev').setEnabled(true);
var cachedCurrent = CacheService.getPublicCache().get('currentItem');
var current;
if (cachedCurrent == null) {
current = 0;
}
else {
current = parseInt(cachedCurrent);
}
var cachedAgendaItems = CacheService.getPublicCache().get('agenda');
var agendaItems;
if (cachedAgendaItems == null) {
agendaItems = [][];
}
else {
agendaItems = Utilities.jsonParse();
}
agendaItems[current]['notes'] = e.parameter.tAreaNotes;
agendaItems[current]['status'] = e.parameter.lboxStatus;
CacheService.getPublicCache().put('agenda', Utilities.jsonStringify(agendaItems));
current = current + 1;
CacheService.getPublicCache().put('currentItem', current);
fillAgendaDetail(app);
// only enabled 'Next' if there are more items in the agenda
if (current < agendaItems.length-1) {
app.getElementById('btnNext').setEnabled(true);
}
return app;
}
Also please mention that the Public Cache (CacheService.getPublicCache()) is the same for all users of your script. In your case, this means, if two users user1#example.com and user2#example.com use the script they will have the same current and agendaItems variables values, i.e. it can be a situation when the _responseToNext handler is already executed under the user1 authority - the current variable is equal to 1, after the user2 executes the _responseToNext handler - the current variable is equal to 2 and so on. If you do not need such behaviour, use the CacheService.getPrivateCache().