I am attempting to compare two text files in a Script Task in an SSIS Package. Both files exist in the file system. Both files are in the same directory. However, one does not exist because the permissions setup do not see the file.
The code below is not working. I have tried a few different variations of the code below and the SSIS Package continues to go forward, ultimately failing on a subsequent File System Task because doesn't have access to the file.
I am attempting to capture that the file is not present because the package does not have access to the file, and not because the file isn't there. Originally, I was using File.Exists(), however, that won't work because it returns false whether the file is not there or the package does not have access to it.
string packageName = Dts.Variables["System::PackageName"].Value.ToString();
string taskName = Dts.Variables["System.TaskName"].Value.ToString();
string inputFilePath = Dts.Variables["User::inputFilePath"].Value.ToString();
string processedFilePath = Dts.Variables["User::processedFilePath"].Value.ToString();
bool blnFilesMatch = true;
try
{
int i = 0, j = 0;
// Compare the source and processed files to determine if the contents are different.
using (var f1 = new FileStream(inputFilePath, FileMode.Open))
using (var f2 = new FileStream(processedFilePath, FileMode.Open))
{
do
{
i = f1.ReadByte();
j = f2.ReadByte();
if (i != j)
break;
} while (i != -1 && j != -1);
if (i != j)
blnFilesMatch = false; // Files Differ
else
blnFilesMatch = true; // Files are the same
}
Dts.Variables["User::blnIdenticalFiles"].Value = blnFilesMatch;
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (FileNotFoundException)
{
string tempFileName = "temp_" + packageName + ".txt.";
string tempFilePath = Path.Combine(Path.GetDirectoryName(inputFilePath), tempFileName);
// A file wasn't found. Try to create and delete a temp file to determine whether it was because of permissions or if the file just was not present.
try
{
File.Create(tempFilePath);
File.Delete(tempFilePath);
Dts.Variables["User::blnIdenticalFiles"].Value = false;
}
catch (UnauthorizedAccessException uae)
{
// Permissions cannot create the file.
Dts.Events.FireError(0, packageName + " - " + taskName, uae.Message, string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
catch (Exception ex)
{
Dts.Events.FireError(0, packageName + " - " + taskName, ex.Message, string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
Related
I am downloading videos from my server in the application sandbox storage, at this path:
final String filePath = this.getExternalFilesDir("videos") + "/" + name + ".mp4";
Now, I want to copy some specific files from the path above to another folder in DCIM so users can discover the videos in the gallery.
I am able to create that file, but I don't understand how to copy and move the file.
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "MyFolder");
if (!dir.exists()) {
boolean rv = dir.mkdir();
Log.d(TAG, "Folder creation " + ( rv ? "success" : "failed"));
}
Can anyone help?
Solved it using standard Java IO stream.
String inputFile = "/" + name + ".mp4";
String inputPath = this.getExternalFilesDir("videos") + "";
String outputPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "MyFolder") + "";
private void copyFile(String inputFile, String inputPath, String outputPath) {
try {
File dir = new File(outputPath);
if (!dir.exists()) {
if (!dir.mkdirs()) {
return;
}
}
try (InputStream inputStream = new FileInputStream(inputPath + inputFile)) {
try (OutputStream outputStream = new FileOutputStream(outputPath + inputFile)) {
File source = new File(inputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
long length = source.length();
long total = 0;
while ((read = inputStream.read(buffer)) != -1) {
total += read;
int progress = (int) ((total * 100) / length);
if (progress == 100) {
Toast.makeText(VideoActivity.this, "Completed", Toast.LENGTH_SHORT).show();
}
outputStream.write(buffer, 0, read);
}
}
}
} catch (Exception e) {
FirebaseCrashlytics.getInstance().recordException(e);
}
}
I need some help with my project.
I have a main method which start a cmd process and redirects output onto event handler.
private void RunBTN_Click(object sender, EventArgs e)
{
this.process.StartInfo.FileName = sMasterBATname;
this.process.StartInfo.UseShellExecute = false;
this.process.StartInfo.CreateNoWindow = true;
this.process.StartInfo.RedirectStandardOutput = true;
this.process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
this.process.StartInfo.RedirectStandardInput = true;
this.process.Start();
this.process.BeginOutputReadLine();
}
CMD process runs number of exe files and everything would be fine but some of the exe output is redirected onto a text file(">>" command) and therefore is not handled by my event.
public void StandardOutputHandler(object sender, DataReceivedEventArgs outLine)
{
if (outLine.Data != null && !String.IsNullOrWhiteSpace(outLine.Data))
{
if (outLine.Data.Contains(">>"))
{
string[] commandLine = outLine.Data.Split('>');
this.logFileFullPath = commandLine[1];
this.logFileFullPath = this.logFileFullPath.Replace('"', ' ').Trim();
string[] split = logFileFullPath.Split('\\');
this.logFileName = split[6];
this.path = split[0] + "\\" + split[1] + "\\" + split[2] + "\\" + split[3] + "\\" + split[4] + "\\" + split[5];
BatchRun.LogMonitor(this.logFileName,this.path) //this class will run on different thread
else
{
//validate content of received data
}
}
}
}
Both methods above are located in partial class.
Log Monitor which will run on separate thread and will perform a loop to check for any updates to the text/log file as per below which is based on Tail like program:
public class Monitor
{
public LogMonitor(string LogName, string LogPath)
{
using (StreamReader reader = new StreamReader(new FileStream(LogName,
FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
//start at the end of the file
long lastMaxOffset = reader.BaseStream.Length;
while (true)
{
System.Threading.Thread.Sleep(100);
//if the file size has not changed, idle
if (reader.BaseStream.Length == lastMaxOffset)
continue;
//seek to the last max offset
reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);
//read out of the file until the EOF
string line = "";
while ((line = reader.ReadLine()) != null)
Console.WriteLine(line);
//update the last max offset
lastMaxOffset = reader.BaseStream.Position;
}
}
}
My issue is that I have no idea how to pass a line variable, each time a new line has been appended to the log, from LogMonitor method onto StandardOutputHandler so I can validate content of the log file the same way and act accordingly.
If someone could use my code and paste an answer that would be awesome. OR maybe someone can suggest a better way of achieving my goal?
I have only been using C# for 2 months so don't have great understanding of the evens etc...
The file you are trying is in a different format than specified by the file extension.Verify that the file is not corrupted and is from a trusted source before opening the file.Do you want to open the file now?
and this 'export to excel' dead the events on the page.
Here is my code
public void ExportToExcelitems(DataTable dt, string fileNameWithoutExt)
{
if (dt.Rows.Count > 0)
{
string filename = fileNameWithoutExt + ".xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
var dgGrid = new GridView();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.HeaderRow.BackColor = System.Drawing.Color.White;
dgGrid.HeaderRow.BackColor = System.Drawing.Color.White;
foreach (GridViewRow row in dgGrid.Rows)
{
row.BackColor = System.Drawing.Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = dgGrid.RowStyle.BackColor;
}
else
{
cell.BackColor = System.Drawing.Color.LightGray;
}
}
}
dgGrid.AutoGenerateColumns = false;
dgGrid.RenderControl(hw);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
}
}
I think you should consider using OpenXML (or more specfically ClosedXML) to build a modern Excel file with the xlsx extension.
Open XML SDK: https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk
Closed XML (nuget): https://www.nuget.org/packages/ClosedXML/
Code Samples: https://github.com/ClosedXML/ClosedXML/wiki/Deliver-an-Excel-file-in-ASP.NET
I am trying to delete an image from directory using following statement
System.IO.File.Delete(Path);
i have previously accessed this image in another function
Image image=Image.FromFile(imagePath)
imageList1.Images.Add(image);
but it shows an error that file is locked by another process. I searched for this and find out that I should use using to dispose of the image object so i tried this
using(Image image=Image.FromFile(imagePath))
imageList1.Images.Add(image);
but this gives me an error in program.cs that paramter is not valid and programs doesnot run.
and sometime it gives the error
Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.
I am adding the imagelist to a list view and before deleting the file i am clearing all the items of both imagelist and listview with following commands.
imageList1.Images.RemoveByKey(imageName);
imageList1.Images.Clear();
listView1.Items.RemoveByKey(imageName);
listView1.Items.Clear();
listView1.SmallImageList = null;
this is my code where i am populating listview.
try
{
string album = albumListBox.SelectedItem.ToString();
List<string> imageName=new List<string>();
XmlDocument doc = new XmlDocument();
doc.Load(Application.StartupPath + "/image.xml");
XmlNodeList list = null;
list = doc.SelectNodes(string.Format("/images/image"));
listView1.Columns.Clear();
listView1.Columns.Add("Image List",210,HorizontalAlignment.Left);
listView1.SmallImageList = imageList1;
listView1.Items.Clear();
imageList1.Images.Clear();
listView1.MultiSelect = false;
foreach (XmlNode node in list)
{
if (node.ChildNodes[2].InnerText == album)
{
string imagePath = Application.StartupPath + "\\images\\" + album + "\\" + node.ChildNodes[0].InnerText;
Image image = Image.FromFile(imagePath);
imageList1.Images.Add(image);
imageName.Add(node.ChildNodes[0].InnerText);
}
}
for (int j = 0; j < this.imageList1.Images.Count; j++)
{
listView1.Items.Add(imageName[j],imageName[j],j);
listView1.View = View.Details;
}
}
catch (Exception e)
{
MessageBox.Show("No Images in this Album Please add the Images");
showImage.Hide();
}
and this is the code where i want to delete the file
var listItem = listView1.SelectedItems[0];
string album = albumListBox.SelectedItem.ToString();
string imageName = listItem.Text;
string imagePath = Application.StartupPath + "\\images\\" + album + "\\" + imageName;
XmlDocument doc = new XmlDocument();
doc.Load(Application.StartupPath + "/image.xml");
XmlNode node = doc.SelectSingleNode(string.Format("//image[./imageName/text()='" + imageName + "' and ./album/text()='" + album + "']"));
if (node != null)
{
//remove image from directory tooV
doc.DocumentElement.RemoveChild(node);
doc.Save(Application.StartupPath + "/image.xml");
imageList1.Images.RemoveByKey(imageName);
imageList1.Images.Clear();
listView1.Items.RemoveByKey(imageName);
listView1.Items.Clear();
listView1.Items[listView1.SelectedIndices[0]].Remove();
imageList1.Images.RemoveAt(listView1.SelectedIndices[0]);
listView1.SmallImageList = null;
fillImageList();
System.IO.File.Delete(imagePath);
MessageBox.Show("Image deleted");
fillAlbumList();
}
So far as the image is still referenced in imagelist1, it is not disposed. In order to properly dispose it, you will have to dispose the imagelist1 also. Then only all the reference to Image are closed.
how to differentiate a Folder Type(Windows/FTP) in MFC(VC++)?
In my case I have a MFC Treeview in which i am adding list of folders coming from server , that folders are Windows and CIFS .Now i want to differentiate internally what type of folder are they because i select some folder and say connect then it brings up login page where i need to login credentials details , but before that i need to differentiate what type of folder is that ?
Any treeview property like setting and geeting key or any other approach.
Thanks in Advance.
I get folder list from server in this format volume1/Folder1,volume2/Folder2||Folder3,Folder4 in this below method i am removing "||" and maintaining them in two differnt variables: strDataFolder contains - FTP Folders and
strNASfolders conatins CIFS folder , then one more method i am using UpdateFolder. If it is FTP then directly Add but if it CIFS check for duplication if that folder is already there dont add it again to treeview.
Now iam not able to get it how to differentiate what type of folder are they ?
void CNDSClientDlg::UpdateSharedFolder(CString strNASfolders,HTREEITEM hChildItem)
{
CString strDataFolder = "";
CString strData = "";
int iPos = 0;
int fPosition = 0;
fPosition = strNASfolders.Find("||");
if(fPosition != -1)
{
strDataFolder = strNASfolders.Mid(0,fPosition);
strNASfolders = strNASfolders.Right(strNASfolders.GetLength()-(fPosition+2));
}
else
{
strDataFolder = strNASfolders;
}
if (strDataFolder != "" )
{
UpdateFolders(strDataFolder,hChildItem,false);
}
if (strNASfolders != "" ) //don't add if already exist
{
UpdateFolders(strNASfolders,hChildItem,true);
}
}
void CNDSClientDlg::UpdateFolders(CString strFolderType,HTREEITEM hChildItem,bool bCheck)
{
int iPos = 0 ;
CString strData = "";
CString strCurrFolder ="";
HTREEITEM HShareFolder = NULL;
bool bFound = false ;
while (iPos != -1)
{
iPos = strFolderType.Find(",");
if (iPos != -1)
{
strData = strFolderType.Mid(0,iPos);//get the folder details
}
else
{
strData = strFolderType;//get the last folder details
}
strFolderType = strFolderType.Right(strFolderType.GetLength()-(iPos+1)); //get remaining data
int fPos = strData.ReverseFind('/');
if (fPos != -1)
{
strCurrFolder = strData.Mid(fPos+1,strData.GetLength()); // get required data
}
else
{
strCurrFolder = strData; //else assign all the data
}
if(bCheck == true)
{
bFound = false ;
HTREEITEM hTempItem = NULL;
CString strItemText = "" ;
hTempItem = m_pTreeview->GetChildItem(hChildItem);
strItemText = m_pTreeview->GetItemText(hTempItem);
while(hTempItem != NULL)
{
if(strItemText != strCurrFolder)
{
strItemText = m_pTreeview->GetItemText(hTempItem);
hTempItem = m_pTreeview->GetNextSiblingItem(hTempItem);
}
else
{
bFound = true;
break;
}
}
}
if(bCheck == false || bFound == false)
{
HShareFolder = m_pTreeview->InsertItem(strCurrFolder,hChildItem);
m_pTreeview->SetItemImage(HShareFolder,2,2);
TTipItemData* pToolTipData ;
pToolTipData = new TTipItemData;
pToolTipData->strTool = strData ;
m_pTreeview->SetItemData(HShareFolder,DWORD(pToolTipData));
}
m_pTreeview->Expand(hParentItem,TVE_EXPAND);
m_pTreeview->EnsureVisible(hParentItem);
}
}
Items in treeviews can have arbitrary data associated with them. Check out:
http://msdn.microsoft.com/en-us/library/ettyybhw(VS.80).aspx
The InsertItem method shown here has an LPARAM parameter. This is for your use, and you can set this to some value that is meaningful to your application.
(EDIT: Alternatively, use one of the least convoluted overloads to insert your item and use CTreeCtrl::SetItemData on the handle that is returned afterwards).
To find out what value is associated with your item, use CTreeCtrl::GetItemData.
Minor Example:
HTREEITEM hItem = m_ctrlTree.InsertItem("My Item", TVI_ROOT);
HTREEITEM hOther = m_ctrlTree.InsertItem("Child Item", hItem);
m_ctrlTree.SetItemData(hItem, static_cast<DWORD_PTR>(10)); // set LPARAM to 10
// note, you can also store pointers! This assumes pObj is some kind of instance
// of a class.
m_ctrlTree.SetItemData(hOther, static_cast<DWORD_PTR>(pObj));
// at a later point:
int myVal = static_cast<int>(m_ctrlTree.GetItemData(hItem));
MyObject* pObj = static_cast<MyObject*>(m_ctrlTree.GetItemData(hOther));