windows service to read emails c# - c#

I am trying to write a windows service which check my outlook inbox every minute.
I have the following code setup.
protected override void OnStart(string[] args)
{
timeDelay = new System.Timers.Timer(30000);
timeDelay = new System.Timers.Timer();
timeDelay.Elapsed += new System.Timers.ElapsedEventHandler(WorkProcess);
timeDelay.Enabled = true;
}
public void WorkProcess(object sender, System.Timers.ElapsedEventArgs e)
{
ReadMyEmail();
}
private void ReadMyEmail()
{
string content;
Application outlookApplication = null;
NameSpace outlookNamespace = null;
MAPIFolder inboxFolder = null;
Items mailItems = null;
try
{
outlookApplication = new Application(); // m getting the error here...
outlookNamespace = outlookApplication.GetNamespace("MAPI");
inboxFolder = outlookNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
mailItems = inboxFolder.Items;
foreach (MailItem item in mailItems)
{
if (item.UnRead)
......
...... all the code for reading emails.
}
}
}
I am getting the following error while i am trying to debug the application.
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
What am I doing wrong here.. I am just trying to read emails using a service.

This should not have been written as a Windows Service. For a "scheduled" application, you could have written this as a normal console application and setup the schedule to run it using Windows Scheduler. You can also set it up to run as you instead of as the system.

Related

Cannot connect to hana database on-premise using C#

I'm trying to follow this tutorial to connect my C# program to HANA Database On-Premise server using SAP DI API, but it does not work for me. I always got an error info like this;
Retrieving the COM class factory for component with CLSID {632F4591-AA62-4219-8FB6-22BCF5F60090} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
This is the code that I used;
private void btnConnection_Click(object sender, EventArgs e)
{
SAPbobsCOM.Company oCompany = new SAPbobsCOM.Company();
try
{
oCompany.CompanyDB = "DBSYS1";
oCompany.Server = "DBSYS1#192.168.xx.xxx";
oCompany.LicenseServer = "DBSYS1#192.168.xx.xxx:30015"; //IP Address of HANAsystem followed by Port number
oCompany.UserName = "username";
oCompany.Password = "password";
oCompany.DbServerType = BoDataServerTypes.dst_HANADB;
oCompany.UseTrusted = true;
int ret = oCompany.Connect();
string errMsg = oCompany.GetLastErrorDescription();
int ErrNo = oCompany.GetLastErrorCode();
if (ErrNo != 0)
{
MessageBox.Show(errMsg);
}
else
{
MessageBox.Show("Connected");
}
}
catch (Exception errMsg)
{
throw errMsg;
}
}
I have tried to find some solutions and I got this link.
It mentioned that the program platform target has to change to x86 or x64. But it still does not work for me.

ISWiRelease Throwing COM Exception in Install Shield Automation

Iam trying to create an Automation in Install Shield,
But Whenever I try to create object of ISWiRelease it throws following exception.
Additional information: Retrieving the COM class factory for component
with CLSID {16C4628B-361F-4739-8D75-4E8FA8C4A348} failed due to the
following error: 80040154 Class not registered (Exception from
HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
I tried changing target platform to x86,Still Iam getting this exception.
Iam using Install Shield 2015 SP2.
DLL which I loaded is ISWiAuto22
Please help me to fix this issue.
Code:
public void BuildProject()
{
ISWiProductConfigs oProdConfigs;
ISWiProductConfig oProdConfig;
ISWiRelease oRelease = new ISWiRelease();
ISWiProject oISWiProj = new ISWiProject();
try
{
//Create IS object
oISWiProj.OpenProject(sProjectFileName, false);
//oISWiProj.ProductVersion = sBuildNumber;
oProdConfigs = oISWiProj.ISWiProductConfigs;
oProdConfig = oProdConfigs[oProdConfigs.Count];
oRelease = oProdConfig.ISWiReleases[1];
oRelease.ProgressIncrement += new __ISWiRelease_ProgressIncrementEventHandler(release_ProgressIncrement);
oRelease.StatusMessage += new __ISWiRelease_StatusMessageEventHandler(this.release_StatusMessages);
oRelease.BuildLocation = sBuildLocation;
oRelease.Build();
oISWiProj.SaveProject();
oISWiProj.CloseProject();
}
catch
{
//log("Build Failed...");
}
finally
{
oRelease.ProgressIncrement -= new __ISWiRelease_ProgressIncrementEventHandler(release_ProgressIncrement);
oRelease.StatusMessage -= new __ISWiRelease_StatusMessageEventHandler(this.release_StatusMessages);
}
}

Is it possible to communicate with AppServiceConnection and uwp in WinForm

Is it possible to communicate with AppServiceConnection and uwp in WinForm? Error: does not contain the definition of "GetAwaiter", this is my code:
Thank you!
This is the code in WinForm:
private AppServiceConnection calculatorService;
static Form1 mainForm;
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
//Add the connection
if (calculatorService == null)
{
calculatorService = new AppServiceConnection();
calculatorService.AppServiceName = "com.yanscorp.appservicedemo.Values";
calculatorService.PackageFamilyName = "c97887ad-1f75-4b48-9e3b-21b89c061715_6evysfdvxt248";
var status = await calculatorService.OpenAsync();//A mistake here
if (status != AppServiceConnectionStatus.Success)
{
string d = "Failed to connect";
return;
}
}
var message = new ValueSet();
message.Add("Request", "GetCallCount");
AppServiceResponse response = await calculatorService.SendMessageAsync(message);//A mistake here
string result = "";
if (response.Status == AppServiceResponseStatus.Success)
{
result = response.Message["Response"] as string;
// Get the data that the service sent to us.
textBlock.Text = result;
}
}
Error:
错误 CS4036 “IAsyncOperation”不包含“GetAwaiter”的定义,并且找不到可接受类型为“IAsyncOperation”的第一个参数的扩展方法“GetAwaiter”(是否缺少针对“System”的 using 指令?) WindowsFormsApplication1
Is it possible to communicate with AppServiceConnection and uwp in WinForm
Yes. You could use App service in WinForm. Check this article for more details.
Error: does not contain the definition of "GetAwaiter"
You could access the Windows 10 APIs in WinForm by reference winmd file and System.Runtime.WindowsRuntime.dll. It looks like you have already referenced winmd , but you may forget to reference System.Runtime.WindowsRuntime.dll which you could find it in the directory C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.
Adding the reference of System.Runtime.WindowsRuntime.dll will resolve your issue. Details please reference Calling Windows 10 APIs From a Desktop Application.

Remote OPC Connected but can't read

I am writing a custom OPC Client application in C#, enabling reading of data from a RSLinx Server.
First of, I wasn't able to connect to the RSLINX Opc Server remotely. Exception Access Denied kept occurring.
I then alteredthe DCOM Settings of MyComputer -> Com Security -> Access Permissions and Launch and Activation Permissions, enabled everything for the User 'Everyone'
This then allowed me to connect, but when It comes to read the server I get the following exception -
[System.Runtime.InteropServices.COMException] {"Exception from HRESULT: 0x80040202"} System.Runtime.InteropServices.COMException
I have scoured the web as much as I possibly can, and they all boil down to Dcom related issues. I have simply tried everything with the Dcom Settings. I have made sure the settings are enabled for both MyComputer and RSLinx server.
I am using two .dll files from OPCFoundation - opcNetApi.dll , opcNetApi.Com.dll
Here is my code, (It may be handy)
private void readplc()
{
Opc.URL url = new Opc.URL("opcda://48.5.0.05/RSLinx OPC Server");
Opc.Da.Server server = null;
OpcCom.Factory fact = new OpcCom.Factory();
server = new Opc.Da.Server(fact, null);
try
{
server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
}
catch (Exception exy)
{
MessageBox.Show(exy.Message);
}
// Create a group
Opc.Da.Subscription group;
Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState();
groupState.Name = "Group";
groupState.Active = true;
group = (Opc.Da.Subscription)server.CreateSubscription(groupState);
// add items to the group.
Opc.Da.Item[] items = new Opc.Da.Item[6];
items[0] = new Opc.Da.Item();
items[0].ItemName = "[ALARM]F20:9";
items[1] = new Opc.Da.Item();
items[1].ItemName = "[ALARM]F22:30";
items[2] = new Opc.Da.Item();
items[2].ItemName = "[ALARM]F22:6";
items[3] = new Opc.Da.Item();
items[3].ItemName = "[ALARM]F18:8";
items[4] = new Opc.Da.Item();
items[4].ItemName = "[ALARM]F22:32";
items[5] = new Opc.Da.Item();
items[5].ItemName = "[ALARM]F22:5";
items = group.AddItems(items);
try
{
group.DataChanged += new Opc.Da.DataChangedEventHandler(OnTransactionCompleted); // COM EXCEPTION THROWN HERE
Console.ReadLine();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Console.ReadKey();
}
}
private void OnTransactionCompleted(object group, object hReq, Opc.Da.ItemValueResult[] items)
{
for (int i = 0; i < items.GetLength(0); i++)
{
}
}
I know for certain that the code works as I have tried building the application connecting as a localhost on the PC I am trying to remote connect to, it reads the data happily.
Hopefully, someone will have some idea what is going on, I have spent over 12 hours in the last 4 working days trying to work it out!
This is working for me:
_opcServer = new Server(_comFactory, null) { Url = new Opc.URL("opcda://localhost/FactoryTalk Gateway") };
_opcServer.Connect();

how to allow permanent access to outlook through C#

I have tried to access and read the outlook mail. I have tried following code but it gives me an security warning popup by saying "A program is trying to access e-mail address information stored in outlook express." when I try to access Microsoft.Office.Interop.Outlook.MailItem in the foreach.
const string OUTLOOK_PROCESSNAME = "OUTLOOK";
const string OUTLOOK_APPLICATIONNAME = "Outlook.Application";
private static Microsoft.Office.Interop.Outlook.Application StartOutlookApplication()
{
return StartApplication(OUTLOOK_PROCESSNAME, OUTLOOK_APPLICATIONNAME) as Microsoft.Office.Interop.Outlook.Application;
}
private static object StartApplication(string processName, string applicationName)
{
// Application object
object app = null;
try
{
// is there an existing application object ?
if (Process.GetProcessesByName(processName).Length > 0)
{
// use the GetActiveObject method to attach an existing application object
app = Marshal.GetActiveObject(applicationName);
}
if (app == null)
{
// create a new instance
Type t = Type.GetTypeFromProgID(applicationName);
app = Activator.CreateInstance(t);
}
}
catch (System.Exception ex)
{
// Some Logging
Trace.WriteLine(string.Format("Error while starting the Application: {0}", applicationName));
}
return app;
}
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
Microsoft.Office.Interop.Outlook.Application app = StartOutlookApplication();
Microsoft.Office.Interop.Outlook.NameSpace NS = app.GetNamespace("MAPI");
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFld = NS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
lastupdateddate = getmostrecentupdatetime();
DateTime lastupdated=Convert.ToDateTime(lastupdateddate);
subFolder = inboxFld.Folders[Inboxpath];
foreach (Microsoft.Office.Interop.Outlook.MailItem t in subFolder.Items)
{
if (t.SenderEmailAddress.Contains(senderemail))
{
Please some one help me.I need to run my program without showing this warning message.
The redemption library will get around most of them.
http://www.dimastr.com/redemption/

Categories