C# Interops error running MS ACCESS macros - c#

I developed a command line app in C# that runs some macros in MS ACCESS but I am getting the following error in the production environment:
System.Runtime.InteropServices.COMException (0x800A09B6): You canĀ“t carry out this action at the present time.
at Microsoft.Office.Interop.Access.DoCmd.RunMacro(Object MacroName, Object RepeatCount, Object RepeatExpression)
When I run the application again it works fine.
This is the code:
public void RunMacros()
{
Application access = null;
_runningMacros = true;
CloseMessageBox("Microsoft Access"); // Thread to close MsgBoxes
try
{
access = new Application();
access.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityLow;
var databases = MdbSettings.Config.Databases;
for (var mdbIndex = 0; mdbIndex < databases.Count; mdbIndex++)
{
if (databases[mdbIndex].Type == ReportType)
{
var mdbFile = databases[mdbIndex].File;
if (mdbFile.StartsWith("OcnTs*", StringComparison.InvariantCultureIgnoreCase))
{
mdbFile = mdbFile.Replace("*", Settings.DateReplaceName);
}
var mdbFullPath = GetFileFullPath(mdbFile, MdbPath);
access.OpenCurrentDatabase(mdbFullPath, Settings.IsDbExclusive);
for (var macrosIndex = 0; macrosIndex < databases[mdbIndex].Macros.Count; macrosIndex++)
{
var macro = databases[mdbIndex].Macros[macrosIndex].Name;
var message = string.Format("{0}, macro: {1}", Path.GetFileName(mdbFullPath), macro);
Log.Write(message);
access.DoCmd.RunMacro(macro);
}
access.CloseCurrentDatabase();
}
}
_runningMacros = false;
access.Quit(Microsoft.Office.Interop.Access.AcQuitOption.acQuitSaveNone);
Marshal.ReleaseComObject(access);
access = null;
}
catch (Exception ex)
{
Log.Write(ex.ToString());
try
{
Marshal.ReleaseComObject(access);
}
catch (Exception e)
{
Log.Write("Error realeasing Access application: " + e.ToString(), Log.Severity.Warning);
}
throw;
}
}
Can someone help me to fix the error?
EDITED:
- The error only occurs in production environment
- The production environment has installed MS Access 2010
- The development environment has installed MS Access 2016
- Every macro run between 6 and 20 queries
- The error does not always occur in the same macro

Related

C# WUApiLib know if a windows update needs a restart

I use this code to get pending windows updates and also most of the informations of the update:
static List<PendingUpdate> GetPendingUpdates()
{
var updateSession = new UpdateSession();
var updateSearcher = updateSession.CreateUpdateSearcher();
updateSearcher.Online = false; //set to true if you want to search online
List<PendingUpdate> pendingUpdates = new List<PendingUpdate>();
try
{
var searchResult = updateSearcher.Search("IsInstalled=0 And IsHidden=0");
if (searchResult.Updates.Count > 0)
{
Console.WriteLine("There are updates available for installation");
foreach (IUpdate windowsUpdate in searchResult.Updates)
{
PendingUpdate update = new PendingUpdate();
update.Title = windowsUpdate.Title;
update.Description = windowsUpdate.Description;
update.Downloaded = windowsUpdate.IsDownloaded;
update.Urls = new List<string>();
foreach (string url in windowsUpdate.MoreInfoUrls)
{
update.Urls.Add(url);
}
foreach (dynamic category in windowsUpdate.Categories)
{
update.Categories += category.Name + ", ";
}
pendingUpdates.Add(update);
}
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR");
throw ex;
}
return pendingUpdates;
}
I also use this code to get to know if the computer currently needs a restart to finish installed updates:
static bool needsRestart()
{
ISystemInformation systemInfo = new SystemInformation();
return systemInfo.RebootRequired;
}
Now my question is, is it possible to get to know if an pending update needs a computer restart to finish? In the first code I get a IUpdate object but I dont see informations about a needed restart after installing this update. I there a way to get this information?
For the asynchronous installation I use something like this:
rebootRequired = false;
UpdateSession updateSession = new UpdateSession();
updateSession.ClientApplicationID = SusClientID;
IUpdateInstaller updatesInstaller = updateSession.CreateUpdateInstaller();
IInstallationJob job = updatesInstaller.BeginInstall(InstallProgressCallback, installComplete, installState);
// here is your installer code and the checking if the installation is completed
IInstallationProgress jobProgress = job.GetProgress();
for (int updateindex = 0; updateindex < updatesInstaller.Updates.Count; updateindex++)
{
IUpdateInstallationResult updateInstallResult = jobProgress.GetUpdateResult(updateindex);
rebootRequired |= updateInstallResult.RebootRequired;
}
if(rebootRequired)
{
// any of the updates need a reboot
}

How can I solve VPN Connection Error in C#

I use a VPN class in my program. But when I try to connect, it cause the following error:
the system could not find the phone book entry for this connection
Here is the connect method:
public void VPN_Connect(string VPN_Name, string VPN_ID, string VPN_PW)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + #"\Microsoft\Network\Connections\Pbk\rasphone.pbk";
AllUsersPhoneBook = new RasPhoneBook();
AllUsersPhoneBook.Open(path);
if (AllUsersPhoneBook.Entries.Contains(EntryName))
{
AllUsersPhoneBook.Entries[EntryName].PhoneNumber = VPN_Name;
AllUsersPhoneBook.Entries[EntryName].Update();
}
else
{
RasEntry entry = RasEntry.CreateVpnEntry(EntryName, VPN_Name, RasVpnStrategy.Default,
RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
entry.EncryptionType = RasEncryptionType.None;
AllUsersPhoneBook.Entries.Add(entry);
}
Dialer = new RasDialer();
Dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(Dialer_DialCompleted);
this.Dialer.EntryName = EntryName;
this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
try
{
this.Dialer.Credentials = new NetworkCredential(VPN_ID, VPN_PW);
this.handle = this.Dialer.DialAsync();
VPN_Status = (int)status.Defalut;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
How can I solve this problem?
I'm also using windows 10 with latest update and DotRas last version.

IncidentResolution Issue CRM SDK - Value can not be null

I'm working on an application which works to anonymise non-production MSCRM environments. My current issue with this is in the process of opening a resolved case (incident), updating and then attempting to resolve the case again.
Opening and updating bare no issues but since recent updates, my re-closure of these cases no longer works.
My code is as follows;
var incidentResolution = new IncidentResolution
{
Subject = "Anonymised Incident Resolved",
IncidentId = new EntityReference(Incident.EntityLogicalName, incId)
};
var closeIncidentRequest = new CloseIncidentRequest
{
IncidentResolution = incidentResolution,
Status = new OptionSetValue(5)
};
if (NotifyValidityOfIncidentSolvedStateChange(_orgServ, statusReason, logiName, incId))
{
try
{
_orgServ.Execute(closeIncidentRequest);
}
catch (Exception ex)
{
string errorMsg = ticket + ex.StackTrace;
}
}
The error that I get is:
"Value cannot be null.\r\nParameter name: value"

Visual C++ 2013 runtime in Service Fabric

I am using TuesPechkin in one of Service Fabric services to generate PDF files from HTML. This is working fine on my local development computer, but as soon as I deploy my application to an Azure cluster and run the same code I get the following error message:
Unable to load DLL 'wkhtmltox.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I think this might be because TuesPechkin relies on the Visual C++ 2013 runtime. Is this supported in a Azure cluster? Or is there something else going wrong?
My code for generating PDF's looks like this:
private static readonly IConverter _converter = new ThreadSafeConverter(
new PdfToolset(
new Win64EmbeddedDeployment(
new AssemblyFolderDeployment())));
public Task<byte[]> GeneratePdfFromHtml(string title, string html)
{
try
{
var document = new HtmlToPdfDocument
{
GlobalSettings = {
ProduceOutline = true,
DocumentTitle = title,
PaperSize = PaperKind.A4, // Implicit conversion to PechkinPaperSize
Margins = {
All = 1.375,
Unit = Unit.Centimeters
}
},
Objects = {
new ObjectSettings { HtmlText = html }
}
};
byte[] result = _converter.Convert(document);
return Task.FromResult(result);
}
catch(Exception e)
{
throw e;
}
}
AssemblyFolderDeployment.cs
public class AssemblyFolderDeployment : IDeployment
{
public string Path
{
get
{
return System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Wkhtml");
}
}
}

Bloomberg web service call for single field and single instrument taking more than 1 min

I am making a Bloomberg web service GetData call for the "DEBT_TO_EQUITY_FUNDAMENTALS_TKR" field. I am setting secmaster = true and asking for a single instrument with a CUSIP identifier (with yellowkey = MarketSector.Corp).
This strikes me as a fairly lightweight call having seen people asking for thousands of instruments and dozens of fields at once.
I have played around with setting lots of different settings but I just can't get this request to return in a few seconds. It gives me the correct return value but it takes longer than 60 seconds.
Any idea if it is possible to get such a request to execute and return in a few seconds?
Thanks
EDIT - Here is the code I am running:
public string GetFundamentalTicker(string identifier, InstrumentType identifierType = InstrumentType.CUSIP)
{
PerSecurityWS ps = new PerSecurityWS();
try
{
log.DebugFormat("Cert path is: {0}", CertPath);
X509Certificate2 clientCert = new X509Certificate2(CertPath, "<password_redacted>");
ps.ClientCertificates.Add(clientCert);
}
catch (Exception e)
{
log.ErrorFormat("Error in cert setup - {0} - {1}", e.Message, e.InnerException == null ? "" : e.InnerException.Message);
return null;
}
//Set request header
GetDataHeaders getDataHeaders = new GetDataHeaders();
getDataHeaders.secmaster = true;
getDataHeaders.secmasterSpecified = true;
//getDataHeaders.fundamentals = true;
//getDataHeaders.fundamentalsSpecified = true;
//getDataHeaders.programflag = ProgramFlag.oneshot;//unnecessary - defaults to this anyway
//getDataHeaders.programflagSpecified = true;
//getDataHeaders.pricing = true;
getDataHeaders.secid = identifierType;
getDataHeaders.secidSpecified = true;
SubmitGetDataRequest sbmtGtDtreq = new SubmitGetDataRequest();
sbmtGtDtreq.headers = getDataHeaders;
sbmtGtDtreq.fields = new string[] {
"DEBT_TO_EQUITY_FUNDAMENTALS_TKR"
};
int currentFundYear = DateTime.Now.Year;
//var fundYears = new List<int>();
List<Instrument> fundYearInstruments = new List<Instrument>();
Instrument fundYearInstrument = null;
fundYearInstrument = new Instrument();
fundYearInstrument.id = identifier;
fundYearInstrument.typeSpecified = true;
fundYearInstrument.type = identifierType;
fundYearInstrument.yellowkey = MarketSector.Corp;
fundYearInstrument.yellowkeySpecified = true;
//fundYearInstrument.overrides = new Override[] {};//{ new Override() { field = "EQY_FUND_YEAR", value = currentFundYear.ToString() } };
fundYearInstruments.Add(fundYearInstrument);
//fundYears.Add(-1);
Instrument[] instr = fundYearInstruments.ToArray();
Instruments instrs = new Instruments();
instrs.instrument = instr;
sbmtGtDtreq.instruments = instrs;
try
{
SubmitGetDataResponse sbmtGtDtResp = ps.submitGetDataRequest(sbmtGtDtreq);
RetrieveGetDataRequest rtrvGtDrReq = new RetrieveGetDataRequest();
rtrvGtDrReq.responseId = sbmtGtDtResp.responseId;
RetrieveGetDataResponse rtrvGtDrResp;
do
{
System.Threading.Thread.Sleep(POLL_INTERVAL);
rtrvGtDrResp = ps.retrieveGetDataResponse(rtrvGtDrReq);
}
while (rtrvGtDrResp.statusCode.code == DATA_NOT_AVAILABLE);
if (rtrvGtDrResp.statusCode.code == SUCCESS)
{
for (int i = 0; i < rtrvGtDrResp.instrumentDatas.Length; i++)
{
for (int j = 0; j < rtrvGtDrResp.instrumentDatas[i].data.Length; j++)
{
if (rtrvGtDrResp.instrumentDatas[i].data[j].value == "N.A." || rtrvGtDrResp.instrumentDatas[i].data[j].value == "N.S." || rtrvGtDrResp.instrumentDatas[i].data[j].value == "N.D.")
rtrvGtDrResp.instrumentDatas[i].data[j].value = null;
return rtrvGtDrResp.instrumentDatas[i].data[j].value;
}
}
return null;
}
else if (rtrvGtDrResp.statusCode.code == REQUEST_ERROR)
{
log.ErrorFormat("Error in the submitted request: {0}", rtrvGtDrResp.statusCode.description);
return null;
}
}
catch (Exception e)
{
log.ErrorFormat("Error in GetData - {0} - {1}", e.Message, e.InnerException == null ? "" : e.InnerException.Message);
return null;
}
return null;
}
Poll interval is 5 seconds and the SOAP web service url is:
https://software.bloomberg.com/datalicensewp/dlws.wsdl
I am having the same issue. I found out that there is a difference between making the same call to Bloomberg API from, for example, console app (works very fast) and web service (takes a lot of time to start session). And the difference is that console app runs under the same user as bbcomm process, whereas web service (or actually iis process) runs under System account. You can try to log out all users on the PC where web service is hosted and then try to make the call. In this case, I guess, bbcomm goes under System account as no one else is logged in and works fast. It worked for me and the call was answered instantly.

Categories

Resources