arcengine isaveas2 Failed to copy raster dataset - raster

The source code are following:
when run into the last pSaveAs.SaveAs... then the computer say "failed to copy raster dataset".
The source code are following:
private void SaveRaster(IRasterDataset2 mygeoDataset,string sFormat,string filePath,string fileName )
{
`ISaveAs2` pSaveAs = mygeoDataset as ISaveAs2;
if(!pSaveAs.CanSaveAs(sFormat))
{
MessageBox.Show("no support file type");
return;
}
IWorkspaceFactory pworspaceFactory = new RasterWorkspaceFactoryClass();
IWorkspace pWorkspace = null;
pWorkspace = pworspaceFactory.OpenFromFile(filePath, 0);
pSaveAs.SaveAs(fileName, pWorkspace, "GRID");
}

Related

Drag an Outlook email into a JavaFX Application

I made a Javafx scene to handle drag-n-drop and it is working fine if you drag a file from the windows explorer or from the desktop for example.
However, if I try to do it from Outlook, the behavior is weird.
I realized that when you drag n drop from another program inside the dragboard component, the method "getContentTypes" will return a few DataFormat objects using this code:
dragField.setOnDragOver((DragEvent event) -> {
Dragboard db = event.getDragboard();
System.out.println(db.getContentTypes());
});
The output will be something like:
[text/plain] - De Objet Reçu Taille Catégories D D Test 13:56 40 Ko [DragImageBits] -
java.nio.HeapByteBuffer[pos=0 lim=90304 cap=90304]
[message/external-body;access-type=clipboard;index=0;name="testEmail.msg"] -
null [Object Descriptor] - java.nio.HeapByteBuffer[pos=0 lim=74
cap=74] [RenPrivateItem] - null [CSV] - java.nio.HeapByteBuffer[pos=0
lim=282 cap=282]
It seems to be able to extract the information from the Outlook msg file, since I got something like a header and also the "testEmail.msg" file name is correct.
However, when I try to use this code:
DataFormat.lookupMimeType("message/external-body;access-type=clipboard;index=0;name=\"testEmail.msg\"");
It returns null... In fact, there is a "null" by the mime-type side.
Is there any way to transform these DataFormat objects into a java file or maybe a apache poi msg file? Anything would be amazing.
Thanks for any help! :D
If there is a mime type starting with message/external-body;access-type=clipboard, you can get the value using
clipboard.getContent(new DataFormat("message/external-body"));
Here is an example which just saves the file:
private boolean clipboardHasInMemoryFile(Clipboard clipboard) {
for (DataFormat d: clipboard.getContentTypes()) {
if (d.toString().startsWith("[message/external-body;access-type=clipboard")) {
return true;
}
}
return false;
}
public void saveOutlookFile() throws IOException {
Clipboard clipboard = Clipboard.getSystemClipboard();
if (clipboardHasInMemoryFile(clipboard)) {
//this is for copying an outlook attachment
String name = "outfile";
for (DataFormat d : clipboard.getContentTypes()) {
if (d.toString().startsWith("[message/external-body;access-type=clipboard")) {
Pattern p = Pattern.compile("name=\"([^\"]*)\"");
Matcher m = p.matcher(d.toString());
m.find();
name = m.group(1);
break;
}
}
Object inMemoryFile = null;
try {
DataFormat df = DataFormat.lookupMimeType("message/external-body");
if (df == null) {
df = new DataFormat("message/external-body");
}
inMemoryFile = clipboard.getContent(df);
} catch (Throwable t) {
}
final String fileName = name;
if (inMemoryFile != null) {
if (inMemoryFile instanceof ByteBuffer) {
ByteBuffer b = (ByteBuffer) inMemoryFile;
byte bytes[] = b.array();
FileOutputStream fo = new FileOutputStream(fileName);
fo.write(b.array());
fo.close();
}
}
}
}

Setting default TWAIN data source without using API UI menu

Using the twaindotnet library in C#, I'm wondering if there's a way to set the default datasource using the library.
As a feeble attempt, I've tried adding a SetDefault method to the DataSource class of twaindonet, like this
public static void SetDefault(Identity applicationId, IWindowsMessageHook messageHook, DataSource newDataSource)
{
var defaultSourceId = newDataSource.SourceId;
// Attempt to get information about the system default source
var result = Twain32Native.DsmIdentity(
applicationId,
IntPtr.Zero,
DataGroup.Control,
DataArgumentType.Identity,
Message.Set,
defaultSourceId);
if (result != TwainResult.Success)
{
var status = DataSourceManager.GetConditionCode(applicationId, null);
throw new TwainException("Error getting information about the default source: " + result, result, status);
}
}
which is called from the DataSourceManage class like this
public void SelectSource(DataSource dataSource)
{
DataSource.Dispose();
DataSource.SetDefault(ApplicationId, _messageHook, dataSource);
}
But when I try to use SetDefault, Twain32Native.DsmIdentity always results in Failure being returned.
I basically copied from SetDefault the setDefaultDataSource method from TWAIN sample Data Source and Application
pTW_IDENTITY TwainApp::setDefaultDataSource(unsigned int _index)
{
if(m_DSMState < 3)
{
cout << "You need to open the DSM first." << endl;
return NULL;
}
else if(m_DSMState > 3)
{
PrintCMDMessage("A source has already been opened, please close it first\n");
return NULL;
}
if(_index >= 0 && _index < m_DataSources.size())
{
m_pDataSource = &(m_DataSources[_index]);
// set the specific data source
TW_UINT16 twrc;
twrc = _DSM_Entry(
&m_MyInfo,
0,
DG_CONTROL,
DAT_IDENTITY,
MSG_SET,
(TW_MEMREF) m_pDataSource);
switch (twrc)
{
case TWRC_SUCCESS:
break;
case TWRC_FAILURE:
printError(0, "Failed to get the data source info!");
break;
}
}
else
{
return NULL;
}
return m_pDataSource;
}
Any help would be greatly appreciated.
The possible cause is that the version of your TWAIN DSM is too low. Only DSM 2.0 or above supports setting default TWAIN data source.

imagemagick file paths? Getting a 'The system cannot find the file specified error'

I cannot figure out where I need to put files for ImageMagick to process them. I am trying to use it in my ASP.NET MVC website and having zero luck having it find my files to process. And if it does how do I specify where they will be output?
I have been looking here and I mut be missing something:
http://www.imagemagick.org/script/command-line-processing.php
Here is my code to call the process:
//Location of the ImageMagick applications
private const string pathImageMagick = #"C:\Program Files\ImageMagick-6.7.3-8";
private const string appImageMagick = "MagickCMD.exe";
CallImageMagick("convert -density 400 SampleCtalog.pdf -scale 2000x1000 hi-res%d.jpg");
private static string CallImageMagick(string fileArgs)
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
Arguments = fileArgs,
WorkingDirectory = pathImageMagick,
FileName = appImageMagick,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
};
using (Process exeProcess = Process.Start(startInfo))
{
string IMResponse = exeProcess.StandardOutput.ReadToEnd();
exeProcess.WaitForExit();
exeProcess.Close();
return !String.IsNullOrEmpty(IMResponse) ? IMResponse : "True";
}
}
We do something similar but use the environment variables (which is advantageous because it works on every system) to execute cmd.exe which we feed with convert and the parameters. This is how we create the ProcessStartInfo object:
// Your command
string command = "convert...";
ProcessStartInfo procStartInfo = new ProcessStartInfo {CreateNoWindow = true};
string fileName = Environment.GetEnvironmentVariable("ComSpec");
if (String.IsNullOrEmpty(fileName))
{
// The "ComSpec" environment variable is not present
fileName = Environment.GetEnvironmentVariable("SystemRoot");
if (!String.IsNullOrEmpty(fileName))
{
// Try "%SystemRoot%\system32\cmd.exe"
fileName = Path.Combine(Path.Combine(fileName, "system32"), "cmd.exe");
}
if ((String.IsNullOrEmpty(fileName)) || (!File.Exists(fileName)))
{
// If the comd.exe is not present, let Windows try to find it
fileName = "cmd";
}
}
procStartInfo.FileName = fileName;
procStartInfo.RedirectStandardInput = true;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
Process proc = Process.Start(procStartInfo);
proc.StandardInput.WriteLine(command);
proc.StandardInput.Flush();
Then we read from proc.StandardOutput in order to get error messages and result codes. Afterwards, we destroy the objects.
Sorry if this is not 100%, I copied it from a more complex OO code.

MethodAccessException when updating a record in sqlite db

I encounter this exception when I try to updating a record with following statement.
UPDATE GroupTable SET groupId=100 WHERE groupId=101
I tested the statement under SQLite Manager of Firefox plug-in, and it works.
The error message is as following image. It crashed at the os_win_c.cs, the method named getTempname().
Well, I modified the original codes and fixed this bug.
The Path.GetTempPath() doesn't work because the sandbox enviroment. It has no access right.
I fixed by following codes. And it works now.
static int getTempname(int nBuf, StringBuilder zBuf)
{
const string zChars = "abcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder zRandom = new StringBuilder(20);
i64 iRandom = 0;
for (int i = 0; i < 20; i++)
{
sqlite3_randomness(1, ref iRandom);
zRandom.Append((char)zChars[(int)(iRandom % (zChars.Length - 1))]);
}
//! Modified by Toro, 2011,05,10
string tmpDir = "tmpDir";
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
store.CreateDirectory(tmpDir);
//zBuf.Append(Path.GetTempPath() + SQLITE_TEMP_FILE_PREFIX + zRandom.ToString());
zBuf.Append(tmpDir + "/" + SQLITE_TEMP_FILE_PREFIX + zRandom.ToString());
return SQLITE_OK;
}
The above patch will result in an extra folder tmpDir in the isolatedstorage, and the temp files won't be deleted automatically, so it needs to be delete by self. I tried to delete those files in tmpDir in the method of winClose inside os_win_c.cs, and I found it will result in crash when I do VACUUM. Finally, I delete those tmp files when I closed the database. The following is a Dispose method in SQLiteConnection class.
public void Dispose()
{
if (_open)
{
// Original codes for close sqlite database
Sqlite3.sqlite3_close(_db);
_db = null;
_open = false;
// Clear tmp files in tmpDir, added by Toro 2011,05,13
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
string tmpDir = "tmpDir";
if (store.DirectoryExists(tmpDir) == false) return;
string searchPath = System.IO.Path.Combine(tmpDir, "*.*");
foreach (string file in store.GetFileNames(searchPath)) {
store.DeleteFile(System.IO.Path.Combine(tmpDir, file));
}
}
}

ASP.NET Backgroundworkers for spreadsheet creation: multiple ones interfering with each other?

I am writing an ASP.NET application in which i need to create multiple excel reports. the report creation is pretty time-consuming (up to ten seconds for each) so i am using backgroundworkers to create them simultaneously.
My code looks a bit like this:
if (condition1)
{
excel_file_name = "TRANSFER";
BackgroundWorker worker_t = new BackgroundWorker();
worker_t.DoWork += new DoWorkEventHandler(DoWork);
worker_t.WorkerReportsProgress = false;
worker_t.WorkerSupportsCancellation = true;
worker_t.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(WorkerCompleted);
worker_t.RunWorkerAsync(excel_file_name);
}
if (Condition2)
{
excel_file_name = "NEFT";
BackgroundWorker worker_n = new BackgroundWorker();
worker_n.DoWork += new DoWorkEventHandler(DoWork);
worker_n.WorkerReportsProgress = false;
worker_n.WorkerSupportsCancellation = true;
worker_n.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(WorkerCompleted);
worker_n.RunWorkerAsync(excel_file_name);
}
there are more conditions but i haven't written them, since they are all similar. the only difference is the Excel_File_Name
the DoWork even then calls a class to create the excel files with the given name.
When condition1 and condition2 are both true, Here is the issue:
1. if i run this slowly using breakpoints during debugging, both files (TRANSFER and NEFT) are created.
2. if, however, i run it without breakpoints like a normal application, only the last file (NEFT in this example) is created.
What can be the issue?
Thanks
PS: For further information, here is the important code from the class that creates the excel file:
private static string placeDataInTemplate(string destFilePath, DataRow dr, bool isCoverLetter)
{
int loop = 0;
ExcelNamespace.Application excelApplication = new ExcelNamespace.Application();
ExcelNamespace.Workbook workbook = excelApplication.Workbooks.Open(destFilePath, 0, false, 5,
"", "", true, ExcelNamespace.XlPlatform.xlWindows, "\t", false, false, 0, true, true, false);
ExcelNamespace.Worksheet workSheet = (ExcelNamespace.Worksheet)workbook.Sheets[sheet_no];
try
{
string value;
string replicate;
string replicate_end;
// get data for Place Holders
sDataTable dtPlaceHolderData = getPlaceHolderData(dr);
//make Display Alerts False
excelApplication.DisplayAlerts = false;
if (dtPlaceHolderData != null && dtPlaceHolderData.Rows.Count > 0)
{
int rowCntDt = 0; //Which row will be used for data?
int i = 1;
Excel.Range Find = (ExcelNamespace.Range)workSheet.Cells.Find("#",
(ExcelNamespace.Range)workSheet.Cells[1, 1],
Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows,
Excel.XlSearchDirection.xlNext,
false,
false,
Missing.Value);
while (Find != null && loop <= 200)
{
loop++;
value = Find.Value2.ToString();
if (condition)
//VERY long if...else if
}
string approveDirPath = destFilePath.Replace(Path.GetFileName(destFilePath), string.Empty);
workbook.Close(true, destFilePath, Type.Missing);
excelApplication.Quit();
string filepath = destFilePath.Split('-')[0];
string approval_id = dr[0].ToString();
return destFilePath;
}
return string.Empty;
}
catch (Exception ex)
{
//do something
}
finally
{
//release resources
}
NOTE: I have removed a lot of needless code. I can paste it if needed. Thank you
Most likely cause is some shared state between two threads - shared state may include excel application and workbooks. So you need to inspect your code for the same.
On the side note, instead of using Excel Automation to generate excel files, you may consider using some in-process library which would be perhaps more scalable and void of such issues. Have a look at one such free basic library at code project

Resources