Process gets stuck in oSession.Logoff() - outlook

Pstcreation works properly with outlook installed.
Now, I am trying to create a pst file with standalone version of MAPI . But my process is stuck in oSession.LogOff(). Further if a comment that oSession.LogOff() line and subsequently call the CreatePstWithRedemption function to create an other pst, the process gets stuck in oSession.LogonPstStore
private bool CreatePstWithRedemption(EmailJTableArgs objJTablArgs, EmailFilterArgs objFilterArgs,
EmailExportRequestParams emailExportRequestParams)
{
RDOSession oSession = null;
IRDOStore store = null;
RDOFolder fFOlder = null;
RDOFolder childFolder = null;
IRDOItems folderItems = null;
var pstCreationStatus = false;
try
{
oSession = new RDOSession();
store = oSession.LogonPstStore(_fileName, 1, "PST");
var folderName = Path.GetFileNameWithoutExtension(_fileName);
if (store != null)
{
fFOlder = store.IPMRootFolder;
foreach (RDOFolder folder in fFOlder.Folders)
{
folder.Delete();
}
childFolder = fFOlder.Folders.Add(folderName, Type.Missing);
folderItems = childFolder.Items;
var resultOfGetEmails = new ResultGetEmails();
resultOfGetEmails.TotalCount = -1;
do
{
var journalEmails = GetEmailList(objFilterArgs, objJTablArgs, emailExportRequestParams,
resultOfGetEmails);
for (var i = 0; i < journalEmails.Count; i++)
{
IRDOMail mail = null;
try
{
mail = folderItems.Add(rdoItemType.olMailItem);
// populate mail fields
mail.Sent = true;
mail.Save();
}
finally
{
if (mail != null)
Marshal.ReleaseComObject(mail);
}
}
resultOfGetEmails.TotalCount -= BatchSize;
objJTablArgs.PageStartIndex += BatchSize;
} while (resultOfGetEmails.TotalCount > 0);
pstCreationStatus = true;
}
}
finally
{
// Do cleanup
if (oSession != null && oSession.LoggedOn)
{
try
{
oSession.Logoff();
Marshal.ReleaseComObject(oSession);
}
catch
{
}
}
}
return pstCreationStatus;
}
Note: The same thing works well when run in an environment where outlook is installed.

Related

TOTP Problem - Microsoft Authenticator is not matching the code generated on server

I am getting a not verified using the TOTP method I have found on the following link.
OTP code generation and validation with otp.net
!My! code is below.
The _2FAValue line at the top is embedded into the QR barcode that Microsoft Authenticator attaches too.
The _Check... Function is the server ajax call to the server which implements OTP.Net library exposing TOTP calculation.
MakeTOTPSecret creates an SHA1 version of a Guid which is applied to the User profile and stored in _gTOTPSecret. NB: This IS populated in the places it is used.
I think I must have missed something obvious to get a result, here.
loSetup2FAData._s2FAValue = $#"otpauth://totp/{loUser.UserName}?secret={loUser.MakeTOTPSecret()}&digits=6&issuer={Booking.Library.Classes.Constants._sCompanyName}&period=60&algorithm=SHA1";
[AllowAnonymous]
public JsonResult _CheckTOTPCodeOnServer([FromBody] Booking.Site.Models.Shared.CheckTotpData loCheckTotpData)
{
string lsMessage = "<ul>";
try
{
string lsEmail = this.Request.HttpContext.Session.GetString("Buku_sEmail");
Booking.Data.DB.Extensions.IdentityExtend.User loUser = this._oDbContext.Users.Where(U => U.UserName.ToLower() == lsEmail.ToLower() || U.Email == lsEmail).FirstOrDefault();
if (loUser != null && loUser.Load(this._oDbContext) && loUser._gTOTPSecret != Guid.Empty)
{
OtpNet.Totp loTotp = new Totp(Booking.Library.Classes.Utility.StringToBytes(loUser.MakeTOTPSecret()), 60, OtpHashMode.Sha1, 6);
loTotp.ComputeTotp(DateTime.Now);
long lnTimeStepMatched = 0;
bool lbVerify = loTotp.VerifyTotp(loCheckTotpData._nTotp.ToString("000000"), out lnTimeStepMatched, new VerificationWindow(2, 2));
if (lbVerify)
{
lsMessage += "<li>Successfully validated Totp code</li>";
lsMessage += "<li>Save is now activated</li>";
return this.Json(new { bResult = true, sMessage = lsMessage + "</ul>" });
}
}
}
catch (Exception loException)
{
lsMessage += "<li>" + Booking.Library.Classes.Utility.MakeExceptionMessage(true, loException, "\r\n", "_CheckTOTPCodeOnServer") + "</li>";
}
lsMessage += "<li>Unsuccessfully validated Totp code</li>";
return this.Json(new { bResult = false, sMessage = lsMessage + "</ul>" });
}
public string MakeTOTPSecret()
{
string lsReturn = String.Empty;
try
{
using (SHA1Managed loSha1 = new SHA1Managed())
{
var loHash = loSha1.ComputeHash(Encoding.UTF8.GetBytes(this._gTOTPSecret.ToString()));
var loSb = new StringBuilder(loHash.Length * 2);
foreach (byte b in loHash)
{
loSb.Append(b.ToString("X2"));
}
lsReturn = loSb.ToString();
}
}
catch (Exception loException)
{
Booking.Library.Classes.Utility.MakeExceptionMessage(true, loException, "\r\n", "Identity.MakeSHA1Secret");
}
return lsReturn;
}

While Mail body being received, how to fetch the Image from multipart body

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.

Catch incoming emails and send them to a web service (rather than just to a mail server)

I would like to catch incoming emails and send them a web service (rather than just to a mail server).
--
After some searching I found a way of getting new emails via polling - see below: This may be of some help to others. Is there a way to receive messages by SMTP? Perhaps by ISAPI ???
using Limilabs.Mail;
using Limilabs.Client.IMAP;
public ActionResult checkIMAPmail()
{
string rval = "not a sausage";
using (Imap imap = new Imap())
{
imap.Connect(<mail server>);
imap.Login(<username>, <password>);
imap.SelectInbox();
List<long> uids = imap.Search(Flag.Unseen);
foreach (long uid in uids)
{
byte[] ourBytes = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(ourBytes);
rval = email.Subject + " [" + email.From + "][" + email.Text + "]";
}
imap.Close();
}
return Content(rval, "text/html");
}
See also http://stackoverflow.com/questions/670183/accessing-imap-in-c-sharp
for other IMAP packages, although note the change to using byte[], above.
Given that Limilabs.Mail is a paid service, I finally used MailKit:
using MailKit;
public int checkIMAPmail()
{
int numEmails = 0;
try {
using (var client = new MailKit.Net.Imap.ImapClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(ourSmtpClient);
// disable the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(ourSmtpAdminUser, ourSmtpAdminUserPwd);
// The Inbox folder is always available on all IMAP servers...
var inboxFolder = client.Inbox;
var savedFolder = client.GetFolder("saved");
inboxFolder.Open(FolderAccess.ReadWrite);
for (int ii = 0; ii < inboxFolder.Count; ii++)
{
var query = MailKit.Search.SearchQuery.NotSeen;
foreach (var uid in inboxFolder.Search(query))
{
var thisMsg = inboxFolder.GetMessage(uid);
string thisDate = notNullString(thisMsg.Date);
string thisSubject = notNullString( thisMsg.Subject);
string thisBody = notNullString(thisMsg.GetTextBody(0)); // plain text
string thisFromName = "";
string thisFromEmail = "";
if ( thisMsg.From != null)
{
// just get the first
foreach( var mb in thisMsg.From.Mailboxes)
{
thisFromName = notNullString( mb.Name);
thisFromEmail = notNullString( mb.Address);
break;
}
}
numEmails += 1;
// move email to saved
inboxFolder.MoveTo(uid, savedFolder);
}
}
client.Disconnect(true);
}
}
catch (Exception exc)
{
log2file("checkIMAPmail Error: " + exc.ToString());
}
return numEmails;
}

ArrayIndex is not supported in LINQ to Entities

// update information from this reponse to database
public bool UpdatePassengerInformation(GetResponse response)
{
try
{
using (MyEntities context = new MyEntities())
{
var masterID = (from Id in context.BookMaster where Id.BookingId == response.BookingId select Id.MasterId).First();
if (masterID != null)
{
for (int i = 0; i < response.Book.Length; i++)
{
var passenger_info = from passenger in context.BookPassenger
where passenger.BookID == masterID &&
assenger.FirstName == response.Book[i].FirstName && passenger.LastName == response.Book[i].LastName select passenger;
// in below loop i got exception "The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities."
foreach (BookPassenger book_passenger in passenger_info)
{
book_passenger.TicketId = response.Book[i].TicketId;
book_passenger.TicketNumber = response.Book[i].TicketNumber;
}
}
context.SaveChanges();
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
}
So don't use it in query, just assign a new variable and use this one.
for (int i = 0; i < response.Book.Length; i++)
{
var responseBook = response.Book[i];
var passenger_info = from passenger in context.BookPassenger
where passenger.BookID == masterID &&
assenger.FirstName == responseBook.FirstName && passenger.LastName == responseBook.LastName select passenger;
foreach (BookPassenger book_passenger in passenger_info)
{
book_passenger.TicketId = responseBook.TicketId;
book_passenger.TicketNumber = responseBook.TicketNumber;
}
}

Images not showing in excel using npoi

The below code which uses npoi to create excel documents displays images in open office calc but not in excel.
If i open the doc in calc and save the document and then open the document in excel i can then see the images in excel.
Here is the code.
public static byte[] CreateExcel(CampaignViewModel viewModel, string fileName)
{
byte[] output;
using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(#"\Data\templates\NPOITemplate.xls"), FileMode.Open, FileAccess.ReadWrite))
{
var templateWorkbook = new HSSFWorkbook(fs, true);
var sheet = templateWorkbook.GetSheet("Sheet1");
var patriarch = sheet.CreateDrawingPatriarch();
var leftFieldHeaders = CsvHelper.GetMatrixAllLeftFields();
var productHeaders = CsvHelper.GetMatrixProducts(viewModel.ProductCampaigns);
var totalCols = leftFieldHeaders.Count + productHeaders.Count;
var colWidth = 5000;
for (int i = 0; i < totalCols; i++)
{
sheet.SetColumnWidth(i, colWidth);
}
var imageRow = sheet.CreateRow(0);
imageRow.Height = 2000;
var imageCellCount = 0;
foreach (var header in leftFieldHeaders)
{
imageRow.CreateCell(imageCellCount).SetCellValue("");
imageCellCount++;
}
foreach (var product in viewModel.ProductCampaigns)
{
try
{
var anchor = new HSSFClientAnchor(0, 0, 0, 0, imageCellCount, 0, imageCellCount, 0);
anchor.AnchorType = 2;
var path = HttpContext.Current.Server.MapPath(product.Product.ImageThumbUrl);
var picture = patriarch.CreatePicture(anchor, LoadImage(#path, templateWorkbook));
picture.Resize();
picture.LineStyle = HSSFPicture.LINESTYLE_SOLID;
}
catch (Exception)
{
}
imageCellCount++;
}
using (MemoryStream ms = new MemoryStream())
{
templateWorkbook.Write(ms);
output = ms.ToArray();
}
}
return output;
}
public static int LoadImage(string path, HSSFWorkbook wb)
{
try
{
var file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
return wb.AddPicture(buffer, PictureType.JPEG);
}
catch (Exception)
{
return 0;
}
}
i've resolved the above in a round about way. Turns out i didn't really need to use the template and could just create the xls from scratch. This add's a bit more meta data to the file which i suspect was the issue
public static byte[] CreateExcel2(CampaignViewModel viewModel, ICollection<DeliveryPoint> deliveryPoints, string fileName)
{
FileContentResult fileContentResult;
byte[] output;
var matrixCampaignLines = viewModel.MatrixCampaignLines;
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hssfworkbook.DocumentSummaryInformation = dsi;
////create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hssfworkbook.SummaryInformation = si;
var sheet = hssfworkbook.CreateSheet("Sheet1");
var patriarch = sheet.CreateDrawingPatriarch();
var leftFieldHeaders = (viewModel.Campaign.EnableNameOnCampaign) ? CsvHelper.GetMatrixAllLeftFields() : CsvHelper.GetMatrixAllLeftFieldsWithoutName();
var productHeaders = CsvHelper.GetMatrixProducts(viewModel.ProductCampaigns);
var totalCols = leftFieldHeaders.Count + productHeaders.Count;
var colWidth = 5000;
for (int i = 0; i < totalCols; i++)
{
sheet.SetColumnWidth(i, colWidth);
}
var imageRow = sheet.CreateRow(0);
imageRow.Height = 2000;
var imageCellCount = 0;
foreach (var header in leftFieldHeaders)
{
imageRow.CreateCell(imageCellCount).SetCellValue("");
imageCellCount++;
}
foreach (var product in viewModel.ProductCampaigns)
{
try
{
var anchor = new HSSFClientAnchor(0, 0, 0, 0, imageCellCount, 0, imageCellCount, 0);
anchor.AnchorType = 2;
var path = HttpContext.Current.Server.MapPath(product.Product.ImageThumbUrl);
var picture = patriarch.CreatePicture(anchor, LoadImage(#path, hssfworkbook));
picture.Resize();//Comment this line if your code crashes.
picture.LineStyle = HSSFPicture.LINESTYLE_SOLID; might not
}
catch (Exception)
{
}
imageCellCount++;
}
using (MemoryStream ms = new MemoryStream())
{
hssfworkbook.Write(ms);
output = ms.ToArray();
}
return output;
}
public static int LoadImage(string path, HSSFWorkbook wb)
{
try
{
var file = new FileStream(path, FileMode.Open, FileAccess.Read);
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
return wb.AddPicture(buffer, PictureType.JPEG);
}
catch (Exception)
{
return 0;
}
}
I got it right now.
I am using
try
{
ISheet sheet = templateWorkbook.GetSheet(sheetName);
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
//create the anchor
HSSFClientAnchor anchor;
anchor = new HSSFClientAnchor(0, 0, 255, 255,
start.Col, start.Row, end.Col, end.Row);
anchor.AnchorType = 2;
patriarch.CreatePicture(anchor,
LoadImage(imagePath, templateWorkbook));
}
catch (IOException ioe)
{
}
and LoadImage() method which returns path from the server.
Use this one. It runs fine.

Resources