Aspose.Cells Password in secured Excel-FIle (c#) - c#

I want to check if the given Password is the password which is locking the Excel-File.
Here is how i tried it:
var DepartmentStream = new FileStream(Deparment, FileMode.Open);
var EmplyoeeStream = new FileStream(Employee, FileMode.Open);
var options = new LoadOptions {Password = "ExamplePassword123"};
DepartmentGrid = new Workbook(DepartmentStream); // set as a Workbook property and doesn't need a password
try
{
EmployeeGrid = new Workbook(EmplyoeeStream , options); // set as a Workbook property
}
catch (Exception ex)
{
EmployeeGrid= null;
}
if (EmployeeGrid == null)
{
MessageBox.Show("The given password is wrong!", "Wrong password",);
return;
}
How can i fix this, so that if the EmployeeGrid's (set as a Workbook property) password isn't the same as the given password the MessageBox get showed and the code leaves the method?

Your code looks to me OK, what's wrong with it? Your current code is trying to load an encrypted (password protected) file with the given password. If your code is not doing what you want, kindly do elaborate your needs, so we could help you accordingly. I will also write another sample code for your complete reference:
e.g
Sample code:
string m_documentFile = "e:\\test2\\EncryptedBook1j.xls";
//Get the password list to store into arrays.
string[] m_passwordList = { "001", "002", "003", "004", "005", "006", "007", "008" };
Workbook _workBook;
int i = 0;
int ncnt = 0;
//Check if the file is password protected.
FileFormatInfo fft = FileFormatUtil.DetectFileFormat(m_documentFile);
bool check = fft.IsEncrypted;
RetryLabel:
try
{
if (check)
{
LoadOptions loadOps = new LoadOptions();
for (i = ncnt; i < m_passwordList.Length; i++)
{
loadOps.Password = m_passwordList[i];
_workBook = new Workbook(m_documentFile, loadOps);
MessageBox.Show("Opened Successfully with the Password:" + m_passwordList[i]);
break;
}
}
}
catch (Exception ex)
{
if (ex.Message.CompareTo("Invalid password.") == 0)
{
MessageBox.Show("Invalid Password: " + m_passwordList[i] + " ,trying another in the list");
ncnt = i + 1;
goto RetryLabel;
}
}
PS. I am working as Support developer/ Evangelist at Aspose.

Related

How to authenticate using username/password/domain via ManagementScope

Have a utility I wrote that checks (among other things) the last time a set of servers was rebooted. This works great as long as the servers are all within my domain and the user launching the app have rights on the servers. Added a section where the user can specify alternative credentials, in our case specifically to deal with another domain. The credentials I am feeding into have domain admin rights on the destination domain, yet my code is getting an Access Denied (Unauthorized Access) error.
thanks!
private void btnLastReboot_Click(object sender, EventArgs e)
{
ConnectionOptions conOpts = new ConnectionOptions();
if (selectedList.Count > 0)
{
Cursor currentCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
stripProgress.Visible = true;
stripProgress.Minimum = 0;
stripProgress.Maximum = selectedList.Count();
stripProgress.Step = 1;
stripProgress.Value = 0;
rtfOut.SelectionTabs = new int[] { 100, 200 };
rtfOut.Text = "";
var sq = new SelectQuery("Win32_OperatingSystem");
if (prefs.useCurrentUser == true)
{
// Setting all fields to NULL causes current user info to be used
conOpts.Username = null;
conOpts.Password = null;
conOpts.Authority = null;
}
else
{
conOpts.Username = prefs.userName;
conOpts.Password = prefs.password.ToString();
conOpts.Authority = "ntlmdomain:" + prefs.domain;
}
foreach (ServerList anEntry in selectedList)
{
stripProgress.Value++;
try
{
var mgmtScope = new ManagementScope("\\\\" + anEntry.ServerName + "\\root\\cimv2", conOpts);
mgmtScope.Connect();
var mgmtSearcher = new ManagementObjectSearcher(mgmtScope, sq);
foreach (var item in mgmtSearcher.Get())
{
var lastBoot = item.GetPropertyValue("LastBootUpTime").ToString();
DateTime lboot = ManagementDateTimeConverter.ToDateTime(lastBoot);
rtfOut.Text += anEntry.ServerName + "\t";
if(anEntry.ServerName.Length <= 9)
{
rtfOut.Text += "\t";
}
rtfOut.Text += lboot.ToLongDateString() + " (" + lboot.ToLongTimeString() + ")\r\n";
}
}
catch (Exception ex)
{
if (ex is UnauthorizedAccessException)
{
rtfOut.Text += anEntry.ServerName + "\t <Access Denied>\r\n";
}
else
{
rtfOut.Text += anEntry.ServerName + "\t <not responding>\r\n";
}
}
}
stripProgress.Visible = false;
Cursor.Current = currentCursor;
}
}
Had to sleep on it, but the answer finally hit me in the shower...
I store the password the user provides in a SecureString variable, but the ConnectionOptions' password field expects the value as a clear string. I was able to test this by temporarily hard coding a password in, which then worked. The final solution was to convert the SecureString to a clear string and then assign it to the ConnectionOption.
If anyone is curious, I used this bit to convert the password back:
string password = new System.Net.NetworkCredential(string.Empty, securePassword).Password;

How to get text of perticular area in scanned file from many file to save with that text to file

I am making small for scanned file reader in c#.
client requirment is to provide facility to select area in scan file by which he can specify which have to read.
I made this using below code
public string ReadCharacter(string fileName)
{
string value = "";
try
{
Image<Emgu.CV.Structure.Gray, byte> img = new Image<Emgu.CV.Structure.Gray, byte>(fileName);
System.Drawing.Rectangle staticRec = new System.Drawing.Rectangle(General.Rect_X, General.Rect_Y, General.Rect_Width, General.Rect_Height);
//img.ROI = staticRec;
var _ocr = new Tesseract(#"D:\", "eng", OcrEngineMode.TesseractCubeCombined);
_ocr.SetVariable("tessedit_char_whitelist", "1234567890");
_ocr.Recognize(img);
General.selectedString = _ocr.GetText();
char[] array1 = { '\n', '\r' };
General.selectedString = General.selectedString.Trim(array1);
img.ROI = staticRec;
_ocr.Recognize(img);
value = _ocr.GetText();
// MessageBox.Show(value);
}
catch (Exception ex)
{
MessageBox.Show("Please Select Valid Area " + ex.Message);
}
// MessageBox.Show(value);
return value;
}
but it not working properly with all files.
Any one can help me please.

How can i get the location of a textfile

I need to get the location of a certain textfile before i user it with sytem.IO methods. I am trying to get an application working on all computer but when i switch between computers it seems to change my D: drive memory pen to and F: drive so the location changes. This is what I have been trying to use:
baseLocation = Application.ExecutablePath;
string UsernameTXT = #PublicVariables.baseLocation + "//userName.txt"
StreamReader user_Login = new StreamReader(UsernameTXT);
string PasswordTXT = #PublicVariables.baseLocation + "//userPass.txt"
StreamReader pass_Login = new StreamReader(PasswordTXT);
while (pass_Login.Peek() != -1)
{
user = user_Login.ReadLine();
pass = pass_Login.ReadLine();
if ((user == textBox1.Text) && (pass == textBox2.Text))
{
MessageBox.Show("Login successful!",
"Success");
}
}
I know this part is wrong:
string UsernameTXT = #PublicVariables.baseLocation + "//userName.txt"
StreamReader user_Login = new StreamReader(UsernameTXT);
string PasswordTXT = #PublicVariables.baseLocation + "//userPass.txt"
StreamReader pass_Login = new StreamReader(PasswordTXT);
its just that i have no idea what to use there instead.
Any help is appreciated.
You may want to have a look at the Path.Combine method that allows you to attach a file name to a path to get the fully qualified file name.
In your example, assuming the files are stored in your Application.StartupPath:
baseLocation = Application.StartupPath;
string usernameFile = Path.Combine(baseLocation, "userName.txt");
string passwordFile = Path.Combine(baseLocation, "userPass.txt");
NOTE: Don't ever store unencrypted passwords!
To read and match a user name with a password, you can then do the following:
var userNameFound = false;
ar passwordMatches = false;
try
{
var ndx = 0
var passwords = File.ReadAllLines(passwordFile);
foreach (var userName in File.ReadAllLines(usernameFile))
{
userNameFound = userName.Equals(textBox1.Text);
if (userNameFound && ndx < passwords.Length)
{
passwordMatches = passwords[ndx].Equals(textBox2.Text);
break; // no need to search further.
}
ndx++;
}
}
catch (FileNotFoundException)
{
MessageBox.Show("Failed to open files", "Error");
}
And report the result like this:
if (userNameFound)
{
if (passwordMatches)
MessageBox.Show("Login successful!", "Success");
else
MessageBox.Show("Incorrect password", "Error");
}
else
{
MessageBox.Show("Incorrect login", "Error");
}
Use this code to get the removable drive name and append your text file name to it
DriveInfo[] ListDrives = DriveInfo.GetDrives();
string driveName=stirng.Empty;
foreach (DriveInfo Drive in ListDrives)
{
if (Drive.DriveType == DriveType.Removable)
{
driveName=Drive.Name;
}
}

Retain the source template when saving slides in ppt

I am trying to save selected slide so it doesnt retain my source template. how do i retain the existing template while i save the slides
private void SaveSelectedSlide_Click(object sender, RibbonControlEventArgs e)
{
try
{
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var temporaryPresentation = Globals.ThisAddIn.Application.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = ppApp.ActivePresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
for (int i = 1; i <= ppslr.Count; i++)
{
var sourceSlide = ppslr[i];
sourceSlide.Copy();
var design = sourceSlide.Design;
temporaryPresentation.Slides.Paste();
}
temporaryPresentation.SaveAs("Temporary", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);
temporaryPresentation.Close();
}
catch (COMException Ex)
{
Debug.WriteLine("Some problem" + Ex.Message + Ex.StackTrace);
MessageBox.Show("PLease enter text ");
}
}
I think I got what you want. When pasting the new slide, save the new SlideRange. Afterwards assign the design of the source slide.
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var temporaryPresentation = Globals.ThisAddIn.Application.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = ppApp.ActivePresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
for (int i = 1; i <= ppslr.Count; i++)
{
var sourceSlide = ppslr[i];
sourceSlide.Copy();
var design = sourceSlide.Design;
SlideRange sr = temporaryPresentation.Slides.Paste(); // get newly created slideRange
sr.Design = sourceSlide.Design; // manually set design
}
temporaryPresentation.SaveAs("Temporary", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);
temporaryPresentation.Close();
It worked for me. Please let me know if this is the expected behaviour!

MAPI_E_FAILONEPROVIDER from Redemption

I'm trying to user Redemption to update a user's Outlook contacts. The user I'm affecting is passed in the exchangeUser, call him "Target User".
This code works when I run it logged in as myself:
public OutlookFolders(string outlookRootFolder, string exchangeUser, string mailServer)
{
var session = new RDOSessionClass();
session.LogonExchangeMailbox(exchangeUser, mailServer);
session.Stores.FindExchangePublicFoldersStore();
var store = session.GetSharedMailbox(exchangeUser);
//...
}
I tried to log in as a 3rd user "Test User" who is not me and is not "Target User". My program brings up a password prompt at runtime when it gets to FindExchangePublicFoldersStore, and if I don't fill in my credentials it fails with the error:
System.Runtime.InteropServices.COMException (0x8004011D): Error in
IMAPISession.OpenMsgStore(pbExchangeProviderPrimaryUserGuid):
MAPI_E_FAILONEPROVIDER
ulVersion: 0
Error: Microsoft Exchange is not available. Either there are network
problems or the Exchange computer is down for maintenance.
Component: Microsoft Exchange Information Store
ulLowLevelError: 2147746069
ulContext: 1318
I tried giving "Test User" owner permission on "Target User's" Mailbox and Contacts folder. Doesn't seem to make a difference. What other permissions need to be set for this to work?
The rule of thumb is to run your code as a user who can access the mailboxes in question, call LogonExchangeMailbox for the current user, then open other users' mailboxes using GetSharedMailbox.
Here's the code for Dmitry's answer.
It also uses a function from Milan's blog.
public OutlookFolders(string exchangeUser, string mailServer)
{
var session = new RDOSessionClass();
var userFullName = GetFullName("DOMAIN-NT\\" + Environment.UserName);
session.LogonExchangeMailbox(userFullName, mailServer);
session.Stores.FindExchangePublicFoldersStore();
var store = session.GetSharedMailbox(exchangeUser);
rootFolder = store.GetDefaultFolder((rdoDefaultFolders)OlDefaultFolders.olFolderContacts);
}
public static string GetFullName(string strLogin)
{
string str = "";
string strDomain;
string strName;
// Parse the string to check if domain name is present.
int idx = strLogin.IndexOf('\\');
if (idx == -1)
{
idx = strLogin.IndexOf('#');
}
if (idx != -1)
{
strDomain = strLogin.Substring(0, idx);
strName = strLogin.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = strLogin;
}
DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
PropertyCollection coll = obDirEntry.Properties;
object obVal = coll["FullName"].Value;
str = obVal.ToString();
}
catch (System.Exception ex)
{
str = ex.Message;
}
return str;
}

Categories

Resources