Checking if a directory is ready System.IO.Directory - asp.net

Is there a way to check if a driver is ready?
Since I am listing all directories, when it reach the dvd for example, I get an exception saying that the driver is not ready.
Thanls a lot
#{
try
{
//Resgata todos os drivers Lógicos do Sistema
string[] drives = System.IO.Directory.GetLogicalDrives();
Response.Write("<ul class=\"jqueryFileTree\" style=\"display: none;\">\n");
//Itera sobre cada driver no array
foreach(string drive in directoryEntries) {
//Para cada driver cria um LI A
Response.Write("\t<li class=\"directory collapsed\">" + drive + "</li>\n");
//Resgata subDiretórios de cada driver
string[] directoryEntries = System.IO.Directory.GetFileSystemEntries(drive);
}
}
catch (Exception)
{
throw;
}
}
thanks a lot

Have a look at the DriveInfo.IsReady property.
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady == true)
{
// do something
}
}
Further information can be found on this MSDN entry:
http://msdn.microsoft.com/en-us/library/system.io.driveinfo.isready.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

Related

Can't set ODBC source at runtime from an ASP.NET Core app hosted in IIS

I have an ASP.NET Core application targeted to use Full .NET Framework 4.6 that contains a part of code where I Create a DSN in ODBC called in Startup.cs:
...
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureSqlContext(Configuration);
services.CrearDSN(Configuration);
...
And in ServiceExtensions.cs:
private const short ODBC_ADD_DSN = 1; //' Add user data source
private const short ODBC_CONFIG_DSN = 2; //' Configure (edit) data source
source
private const int vbAPINull = 0;
public static void CrearDSN(this IServiceCollection services, IConfiguration config)
{
//DSNBaseOperativa = Replace(Left((My.Settings.Servidor & My.Settings.BaseDatos & Application.ProductName), 32), "\", "") 'El nombre tiene como maximo 32 caracteres.
//IOptions<ConnectionODBC> odbcsettings;
string Driver = "SQL Server";
int ReturnValue;
string Attributes;
//string name = config["SQLconnection:Server"] + config["SQLconnection:Database"] + "InteliBS";
string name = config["SQLConnection:Server"] + config["SQLConnection:Database"] + "InteliBS";
string DSNBaseOperativa = name.Length > 32 ? name.Substring(0, 32).Replace( "\\", "") : name.Replace("\\", ""); //'El nombre tiene como maximo 32 caracteres.
Attributes = "SERVER=" + config["SQLConnection:Server"] + "\0";
Attributes += "DESCRIPTION=Temp DSN" + "\0";
Attributes += "DSN=" + DSNBaseOperativa + "\0";
Attributes += "DATABASE=" + config["SQLConnection:Database"] + "\0";
//'To show dialog, use Form1.Hwnd instead of vbAPINull.
ReturnValue = SQLConfigDataSource(vbAPINull, ODBC_ADD_DSN, Driver, Attributes); //TODO: Poder regresar el valor en debug o pararlo en caso 0
if (ReturnValue != 0){
System.Diagnostics.Debug.WriteLine("Se ha cargado un DSN de ODBC: " + DSNBaseOperativa, "INFO");
config["ConnectionODBC:DSN"] = DSNBaseOperativa;
config["ConnectionODBC:Description"] = "Temp DSN";
config["ConnectionODBC:Server"] = config["SQLConnection:Server"];
config["ConnectionODBC:Database"] = config["SQLConnection:Database"];
config["ConnectionODBC:Userid"] = config["SQLConnection:Userid"];
config["ConnectionODBC:Password"] = config["SQLConnection:Password"];
services.Configure<ConnectionODBC>(config.GetSection("ConnectionODBC"));
}
else
{
System.Diagnostics.Debug.WriteLine("No se pudo crear un DSN de ODBC", "INFO");
}
}
// Use DllImport to import the Win32 SQLConfigDataSource function.
[DllImport("ODBCCP32.DLL", CharSet = CharSet.Ansi)]
private static extern int SQLConfigDataSource(int hwndParent, int ByValfRequest, string lpszDriver, string lpszAttributes);
Maybe are you wondering why I'm trying to configure an ODBC instead a regular SQL connection string. The reason is a legacy library that requires that in some parts of the application that I won't explain. Everything else use Entity Framework as usual.
When I run my application from Visual Studio 2017 using IISExpress, works like a charm. It creates an ODBC User Source with no problem in case doesn't exist.
But when I try to host it an IIS server on Windows Server 2012 R2, it doesn't work. Is there a restriction from IIS8 that prevents that?
The user as whom IIS was running did not have the necessary permissions.
Selecting a different user from the application pool for this application resolved the issue.

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();
}
}
}
}

Message Stucks (Microsoft.Samples.BizTalk.Adapter.Common )

We use Microsoft.Samples.BizTalk.Adapter.Common library for our custom SMTP Receive Adapter. Everything seems fine except one situation. The message stucks if it larger than approximatly 5 MB and it includes more than two attachments. Our adapter is run on isoletadHost. In query window we see that the message stay in active status. During our investigation we found that it stucks in a batch.Wait() method. Any other messages handling well. We are running Biztalk 2006 Standart.
Could anyone provide us with any suggestion?
SyncReceiveSubmitBatch batch = new SyncReceiveSubmitBatch(transportProxy, terminator, 1);
Int32 count = 0;
foreach (IBaseMessage msg in messages)
{
try
{
batch.SubmitMessage(msg, null);
count++;
}
catch (Exception ex)
{
try
{
msg.SetErrorInfo(ex);
batch.MoveToSuspendQ(msg);
ThreadContext.Properties["EventID"] = 1007;
logger.Error("Submit Error", ex);
}
catch (Exception ex2)
{
ThreadContext.Properties["EventID"] = 1008;
logger.Error("Suspend Error", ex2);
}
}
}
if (count != 0)
{
batch.Done();
if (batch.Wait())
{
ThreadContext.Properties["EventID"] = 1009;
logger.Debug("Messages publised");
}
else
{
ThreadContext.Properties["EventID"] = 1010;
logger.Warn(String.Format("Publish error. Sucssefully publised {1}, error in {0} messages", batch.FailedMessages.Count, count - batch.FailedMessages.Count));
}
}
else
{
ThreadContext.Properties["EventID"] = 1011;
logger.Warn("No message found");
}
This fix: http://support.microsoft.com/kb/928078 helped to solve the problem. Thanks all.

AspxPivotGrid and WebCharControl Issues

I've got two questions/issues regarding the AspxPivotGrid.
When I use the customization window and add columns in the 'Row Area' and 'Data Area' and update the report. The grid generates properly but the graph doesn't generate. However when you add a field in the 'Column Area', the graph then generates.
It appears that the graph only generates when there are at least a column specified, even though the 'Data Area' headers is exactly the data we need. I have simulated this with the graph demo you have on your site. Is this expected behavior?
Secondly, when I add a DateTime to the 'Row Area' and a String 'Column Area' it's fine. I then swap the columns around, again the pivot is fine. Switch it back again you get the following error:
System.ArgumentException: The type of the "Arguments" argument data member isn't compatible with the date-time scale.
at DevExpress.XtraCharts.SeriesBase.CheckArgumentDataMember(Object dataSource, String dataMember, ScaleType argumentScaleType)
Any suggestions / solutions?
If you have fields in the 'Row Area' and 'Data Area', but not in the 'Column Area', the grid shows the column grand totals. You can show these in the chart by setting the ShowColumnGrandTotals property, e.g.:
ASPxPivotGrid1.OptionsChartDataSource.ShowColumnGrandTotals = True
The default value of not showing grand totals is understandable, since most charts show either:
aggregate values grouped by a row or
column field, but no grand totals, or
only grand total values from rows or
columns.
I was having the same errors:
The type of the "Arguments" argument data member isn't compatible with the numeric scale
The type of the "Arguments" argument data member isn't compatible with the datetime scale
It was happening when user changed the rows by columns or vice-versa in the pivot grid. To workaround this issue, i tried this code, and it works for me:
//Always make the chart visible then perform DataBind() //Sempre deixar o gráfico visivel e depois executar o método DataBind()
try
{
dxGrafico.Visible = true;
dxGrafico.RefreshData();
dxGrafico.DataBind();
}
catch (Exception ex)
{
//Try to fix the error: The type of the "Arguments" argument data member isn't compatible with the <data type> scale //Tentar corrigir o Erro
bool bTeste = false;
bTeste = Ajuste_Grafico_ScaleType(ex);
//If not fix the argument scale type, then show error message label //Se não conseguir corrigir , acrescenta um label com texto da mensagem de erro
if (!bTeste)
{
//Make the chart not visible and Add a label on the Page Control that the owners the chart //Deixar o gráfico invisível e exibir o label com mensagem no objeto PageControl que contém o gráfico
dxGrafico.Visible = false;
try
{
//Error Message (Mensagem de Erro)
ASPxLabel lbl = new ASPxLabel();
lbl.ID = "lblMensagemErroGrafico";
lbl.Text += "\n\n" + "ATENÇÃO: Não Foi possível Processar o Gráfico" + "";
lbl.Text += "\n\n" + "Tente utilizar outro tipo de Gráfico" + "";
lbl.Text += "\n\n" + ex.Message + ""; //lbl.Text += "\n\n" + ex.ToString() + "";
this.pgControl.TabPages[1].Controls.Add(lbl);
}
catch (Exception ex1) { }
}
}
//method Try to fix the error
private bool Ajuste_Grafico_ScaleType(Exception exOrigem)
{
//Try to fix error argument ArgumentScaleType (Tenta ajustar erro)
bool saida = false;
try
{
//Auto
try
{
dxGrafico.SeriesTemplate.ArgumentScaleType = ScaleType.Auto;
dxGrafico.DataBind();
dxGrafico.SeriesTemplate.ValueScaleType = ScaleType.Auto;
dxGrafico.DataBind();
saida = true;
return saida;
}
catch (Exception e) { }
//Numeric
try
{
int n = exOrigem.Message.ToString().IndexOf("Numeric", 0, StringComparison.OrdinalIgnoreCase);
if (n >= 0)
{
dxGrafico.SeriesTemplate.ArgumentScaleType = ScaleType.DateTime;
dxGrafico.DataBind();
dxGrafico.SeriesTemplate.ValueScaleType = ScaleType.DateTime;
dxGrafico.DataBind();
saida = true;
return saida;
}
}
catch (Exception e) { }
//Date Time
try
{
int n = exOrigem.Message.ToString().IndexOf("Date", 0, StringComparison.OrdinalIgnoreCase);
if (n >= 0)
{
dxGrafico.SeriesTemplate.ArgumentScaleType = ScaleType.Numerical;
dxGrafico.DataBind();
dxGrafico.SeriesTemplate.ValueScaleType = ScaleType.Numerical;
dxGrafico.DataBind();
saida = true;
return saida;
}
}
catch (Exception e) { }
}
finally
{
}
return false;
}
It works for the most chart types, but to FullStakedLine happened another error not related here.

SQL CE 3.5 problem with TableDirect table access

I try to insert hundreds of records into empty database table using TableDirect type of SqlCeCommand. The problem is I get an exception SqlCeException "Unspecified error" when calling SqlCeResultSet::Insert. Below is my code. Any hints?
Thanks
public bool StoreEventsDB2(List<DAO.Event> events)
{
try
{
SqlCeCommand command = new SqlCeCommand("Event");
command.CommandType = System.Data.CommandType.TableDirect;
SqlCeResultSet rs = _databaseManager.ExecuteResultSet(command, ResultSetOptions.Updatable | ResultSetOptions.Scrollable );
foreach (DAO.Event theEvent in events)
{
SqlCeUpdatableRecord record = rs.CreateRecord();
record.SetInt32( 0, theEvent.ID );
record.SetInt32( 1, theEvent.ParentID);
record.SetString(2, theEvent.Name);
record.SetDateTime(3, theEvent.DateTime);
record.SetDateTime(4, theEvent.LastSynced);
record.SetInt32(5, theEvent.LastSyncedTS);
record.SetString(6, theEvent.VenueName);
record.SetBoolean(7, theEvent.IsParentEvent);
record.SetDateTime(11, DateTime.Now);
rs.Insert(record);
}
}
catch (SqlCeException e)
{
Log.Logger.GetLogger().Log(Log.Logger.LogLevel.ERROR, "[EventManager::StoreEventsDB] error: {0}", e.Message);
return false;
}
catch (Exception e)
{
Log.Logger.GetLogger().Log(Log.Logger.LogLevel.ERROR, "[EventManager::StoreEventsDB] error: {0}", e.Message);
return false;
}
return true;
}
I am unsure how your connection is managed with the database manager which could be the culprit - make sure you are using one connection (sqlce doesn't play nice). Also the results set option "ResultSetOption.Scrollable" is not needed (at least I have never used it for an insert).
Below is the syntax I use when doing direct table inserts. Every database/data access object is wrapped in a using statement to dispose of objects after use - this is very important especially with the compact framework and sqlce as the garbage collection is less than ideal (you WILL get out of memory exceptions!). I have added a transaction to your code also so that the option is all or nothing.
Hope this helps:
using (var transaction = connection.BeginTransaction())
{
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandType = CommandType.TableDirect;
command.CommandText = "Event";
using (var rs = command.ExecuteResultSet(ResultSetOptions.Updatable))
{
var record = rs.CreateRecord();
foreach (DAO.Event theEvent in events)
{
record.SetInt32(0, theEvent.ID);
record.SetInt32(1, theEvent.ParentID);
record.SetString(2, theEvent.Name);
record.SetDateTime(3, theEvent.DateTime);
record.SetDateTime(4, theEvent.LastSynced);
record.SetInt32(5, theEvent.LastSyncedTS);
record.SetString(6, theEvent.VenueName);
record.SetBoolean(7, theEvent.IsParentEvent);
record.SetDateTime(11, DateTime.Now);
rs.Insert(record);
}
}
transaction.Commit();
}
}

Resources