WPF-从内部类调用父函数? [英] WPF - Calling parent function from Internal Class?

查看:70
本文介绍了WPF-从内部类调用父函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我在尝试从附加到Quartz.NET的内部类中调用函数时遇到一些问题.我进行了一些谷歌搜索,并(针对不良术语使用了策略)看起来像通常将基础(MainWindow)附加到内部类上.不幸的是,当我这样做时,Quartz停止工作.

问题?
如何在不破坏以下(IMyJob)接口的情况下从内部类调用基类中的函数?

代码

Hello All,
I am having some issues trying to call a function from an internal class attached to Quartz.NET. I did some googling and (apoligies for the bad terminology) it looks like normally you attach the base (MainWindow) to the internal class. Unfortunately when I do this, Quartz stops working.

The Question?
How do I call a function in the Base Class from an Internal Class without breaking the following (IMyJob) interface?

The Code

internal class SendAlarmCommand : MainWindow, IMyJob
{
    public void Execute(JobExecutionContext context)
    {
        Console.WriteLine("In MyJob class : " + context.JobDetail.Name);
        Console.WriteLine(string.Format("Running Alarm Job - {0}", System.DateTime.Now.ToString("r")));

        JobDataMap dataMap = context.JobDetail.JobDataMap;

        Console.WriteLine("Client ID - " + dataMap.GetString("ClientID"));
        Console.WriteLine("Clock ID - " + dataMap.GetString("ClockID"));
        Console.WriteLine("Command - " + dataMap.GetString("Command"));

        string command = (dataMap.GetString("Command"));
        Send(command); //Function in Main Window
    }
}

internal interface IMyJob : IJob
{
}



抱歉,所提供的信息很少,我希望足够.我对这种事情还很陌生.

谢谢您提前提供的所有帮助,
Alex



Sorry for the the little information, I hope it''s enough. I''m still quite new to this sort of thing.

Thank you for all your help in advance,
Alex

推荐答案

您的接口没有成员,因此由于实现了该接口,因此其实现可能不会中断".在更一般的情况下,这也不是问题:任何类的任何方法都可以调用任何类的任何方法(静态方法)或类实例(实例方法),而与接口实现无关.您可能面临的唯一问题是成员的声明与接口的成员冲突,但是可以使用 explicit接口成员实现解决此问题,请参见http://msdn.microsoft.com/en-us/library/ms173157.aspx [
—SA
Your interface has no members, so its implementation cannot be possibly "broken" due to the fact this interface is implemented. In more general case, it is also not a problem: any method of any class can call any method of any class (static method) or a class instance (instance method) without any concerns related to interface implementation. The only problem you might face is declaration of members conflicting with the members of interface, but this problem is resolved using explicit interface member implementation, see http://msdn.microsoft.com/en-us/library/ms173157.aspx[^].

If you face some problem ("stops working"), the reason is somewhere else; you did not provide enough information to see it.

—SA


Hello Sa,
感谢您的答复,但我在理解方面有些麻烦...
我浏览了一下代码,似乎找不到任何会引起冲突的东西,并且运行该程序也没有问题.唯一的问题是当我添加基类(
Hello Sa,
Thank you for the reply but I am having a little trouble understanding...
I had a look through the code and I can''t seem to find anything that would cause a conflict and the is no problem running the program. The only issue is when I add the base class (
internal class SendAlarmCommand : MainWindow, IMyJob

)时,Quartz不会触发作业.

以下是我尝试使用的所有代码...如果您可以看一下,将不胜感激.

再次感谢您的帮助,
亚历克斯.


) Quartz does not trigger the Job.

Below is the all the code I am trying to get working... If you could take a look, that would be greatly appreciated.

Thank you again for your help,
Alex.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Common.Logging;
using Quartz;
using Quartz.Impl;
using System.Threading;
using System.Net;
using System.ComponentModel;
using Scheduler.SVC;
using System.Configuration;
using System.Windows.Threading;
using System.ServiceModel;

namespace Scheduler
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, SVC.ICommsCallback
    {
        static IScheduler _scheduler;

        static string ServerIPAddress;
        static string UnitName;

        static ScheduleDataContext ScheduleDC = new ScheduleDataContext();
        static ClientDataContext ClientDC = new ClientDataContext();

        SVC.CommsClient proxy = null;
        SVC.Client receiver = null;
        SVC.Client localClient = null;

        private delegate void FaultedInvoker();

        Dictionary<string, SVC.Client> OnlineClients = new Dictionary<string, Client>();    

        public MainWindow()
        {
            InitializeComponent();

            //Get configuration information from app.config
            ServerIPAddress = ConfigurationManager.AppSettings["ServerAddress"];
            UnitName = ConfigurationManager.AppSettings["DeviceName"];

            //Start Quartz
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler();
            _scheduler.Start();
            Console.WriteLine("Scheduler Started");
        }

        protected override void OnInitialized(EventArgs e)
        {
            this.Loaded += new RoutedEventHandler(Scheduler_Loaded);
            this.Closed += new EventHandler(Scheduler_Closed);
            base.OnInitialized(e);
        }

        private void Scheduler_Loaded(object sender, RoutedEventArgs e)
        {
            //Add active Alarm jobs to _scheduler
            var AlarmsQuery = from aq in ScheduleDC.schedule_ALARMs
                              where aq.alarm_STATE == 1
                              select aq;

            foreach (var aq in AlarmsQuery)
            {
                AddAlarmJob(aq.alarm_ID, Convert.ToInt16(aq.client_ID), Convert.ToInt16(aq.clock_ID), aq.time_CRON, aq.command);
            }

            //Connect to ServiceHost
            proxy = null;
            Connect();
        }

        private void Scheduler_Closed(object sender, EventArgs e)
        {
            //Disconnect from ServiceHost
            if (proxy != null)
            {
                if (proxy.State == CommunicationState.Opened)
                {
                    proxy.Disconnect(this.localClient);
                    Console.WriteLine("Disconnected from server");
                }
                else
                {
                    HandleProxy();
                }
            }

            //Shutdown Quartz
            _scheduler.Shutdown();
        }

        public void AddAlarmJob(int AlarmID, int ClientID, int ClockID, string TimeCRON, string Command)
        {
            string JobName = ("AlarmJob" + AlarmID);
            string TriggerName = ("AlarmTrigger" + AlarmID);

            JobDetail jobDetail = new JobDetail(JobName, null, typeof(SendAlarmCommand));

            jobDetail.JobDataMap["ClientID"] = Convert.ToString(ClientID);
            jobDetail.JobDataMap["ClockID"] = Convert.ToString(ClockID);
            jobDetail.JobDataMap["Command"] = Command;

            CronTrigger trigger = new CronTrigger(TriggerName, null, TimeCRON); //run at 2am every day - use CronMaker
            _scheduler.ScheduleJob(jobDetail, trigger);

            DateTime JobTimeUTC = Convert.ToDateTime(trigger.GetNextFireTimeUtc());
            DateTime JobTimeLocal = JobTimeUTC.ToLocalTime();
            Console.WriteLine("Job Added - " + JobName);
            Console.WriteLine("Next Fire Time: " + JobTimeLocal);
        }

        public static void UpdateTVGuide(string GuideID, string GuideURL)
        {
            string JobName = ("TVGuideUpdateJob" + GuideID);
            string TriggerName = ("TVGuideUpdateTrigger" + GuideID);

            //IMyJob myJob = new TVGuideUpdate(); //This Constructor needs to be parameterless
            JobDetail jobDetail = new JobDetail(JobName, null, typeof(TVGuideUpdate));

            jobDetail.JobDataMap["GuideURL"] = GuideURL;

            CronTrigger trigger = new CronTrigger(TriggerName, null, "0 15 18 * * ? *"); //run at 2am every day - use CronMaker
            _scheduler.ScheduleJob(jobDetail, trigger);

            DateTime JobTimeUTC = Convert.ToDateTime(trigger.GetNextFireTimeUtc());
            DateTime JobTimeLocal = JobTimeUTC.ToLocalTime();
            Console.WriteLine("Job Added - " + JobName);
            Console.WriteLine("Next Fire Time:" + JobTimeLocal);
        }

        # region COMMS - Private Methods

        private void HandleProxy()
        {
            if (proxy != null)
            {
                switch (this.proxy.State)
                {
                    case CommunicationState.Closed:
                        proxy = null;
                        break;
                    case CommunicationState.Closing:
                        break;
                    case CommunicationState.Created:
                        break;
                    case CommunicationState.Faulted:
                        proxy.Abort();
                        proxy = null;
                        break;
                    case CommunicationState.Opened:

                        Console.WriteLine("Connection Successful");

                        break;
                    case CommunicationState.Opening:
                        break;
                    default:
                        break;
                }
            }

        }

        private void Connect()
        {
            Console.WriteLine("Connecting to server, please wait a moment...");

            if (proxy == null)
            {
                try
                {
                    this.localClient = new SVC.Client();
                    this.localClient.Name = UnitName;
                    this.localClient.UnitType = 1;
                    InstanceContext context = new InstanceContext(this);
                    proxy = new SVC.CommsClient(context);

                    proxy.Endpoint.Address = new EndpointAddress("net.tcp://" + ServerIPAddress + ":6555/ServiceHost/tcp");

                    proxy.Open();

                    proxy.InnerDuplexChannel.Faulted += new EventHandler(InnerDuplexChannel_Faulted);
                    proxy.InnerDuplexChannel.Opened += new EventHandler(InnerDuplexChannel_Opened);
                    proxy.InnerDuplexChannel.Closed += new EventHandler(InnerDuplexChannel_Closed);
                    proxy.ConnectAsync(this.localClient);
                    proxy.ConnectCompleted += new EventHandler<ConnectCompletedEventArgs>(proxy_ConnectCompleted);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Epic Fail" + ex);
                }
            }
            else
            {
                HandleProxy();
            }
        }

        void proxy_ConnectCompleted(object sender, ConnectCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Console.WriteLine(e.Error.Message.ToString());
            }
            else if (e.Result)
            {
                HandleProxy();
            }
            else if (!e.Result)
            {
                Console.WriteLine("Name found");
            }


        }

        private void Send(string Command)
        {
            if (proxy != null)
            {
                if (proxy.State == CommunicationState.Faulted)
                {
                    HandleProxy();
                    Console.WriteLine("Failed");
                }
                else
                {
                    SVC.Message msg = new SVC.Message();
                    msg.Sender = this.localClient.Name;
                    msg.Content = Command;

                    proxy.SendAsync(msg);

                    proxy.IsWritingAsync(null);
                }
            }
        }

        private void SendPrivate(string command)
        {
            if (proxy != null)
            {
                if (proxy.State == CommunicationState.Faulted)
                {
                    HandleProxy();
                }
                else
                {
                    SVC.Message msg = new SVC.Message();
                    msg.Sender = this.localClient.Name;
                    msg.Content = (command);

                    proxy.SendPrivateAsync(msg, this.receiver);

                    proxy.IsWritingAsync(null);
                }
            }
        }

        public void ProccessMessage(string command)
        {

        }

        public void ProccessPrivateMessage(string command)
        {

        }

        #endregion

        #region COMMS - IChatCallback Members

        public void RefreshClients(List<Scheduler.SVC.Client> clients)
        {
            OnlineClients.Clear();
            foreach (SVC.Client c in clients)
            {
                OnlineClients.Add(c.Name, c);
            }
        }

        public void Receive(Scheduler.SVC.Message msg)
        {

        }

        public void ReceivePrivate(Scheduler.SVC.Message msg, Scheduler.SVC.Client receiver)
        {
            Console.WriteLine(msg.Sender + " whispers " + receiver.Name + " : " + msg.Content);
        }

        public void IsWritingCallback(Scheduler.SVC.Client client)
        {
            if (client == null)
            {
                //chatLabelWritingMsg.Content = "";
            }
            else
            {
                //chatLabelWritingMsg.Content += client.Name +
                //      " is writing a message.., ";
            }
        }

        public void ClientConnect(Scheduler.SVC.Client client)
        {
            //MessagesListBox.Items.Add(client.UnitType + "------------ " + client.Name + " joined chat ------------");
        }

        public void ClientDisconnect(Scheduler.SVC.Client client)
        {
            //MessagesListBox.Items.Add(client.UnitType + "------------ " + client.Name + " left chat ------------");
        }

        #endregion

        # region COMMS - InnerDuplexChannel

        void InnerDuplexChannel_Closed(object sender, EventArgs e)
        {
            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                new FaultedInvoker(HandleProxy));
                return;
            }
            HandleProxy();
        }

        void InnerDuplexChannel_Opened(object sender, EventArgs e)
        {
            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                new FaultedInvoker(HandleProxy));
                return;
            }
            HandleProxy();
        }

        void InnerDuplexChannel_Faulted(object sender, EventArgs e)
        {
            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                new FaultedInvoker(HandleProxy));
                return;
            }
            HandleProxy();
        }

        #endregion

        #region COMMS - Async

        public IAsyncResult BeginClientDisconnect(Scheduler.SVC.Client client, AsyncCallback callback, object asyncState)
        {
            throw new NotImplementedException();
        }

        public void EndClientDisconnect(IAsyncResult result)
        {
            throw new NotImplementedException();
        }

        public IAsyncResult BeginClientConnect(Scheduler.SVC.Client client, AsyncCallback callback, object asyncState)
        {
            throw new NotImplementedException();
        }

        public void EndClientConnect(IAsyncResult result)
        {
            throw new NotImplementedException();
        }

        public IAsyncResult BeginIsWritingCallback(Scheduler.SVC.Client client, AsyncCallback callback, object asyncState)
        {
            throw new NotImplementedException();
        }

        public void EndIsWritingCallback(IAsyncResult result)
        {
            throw new NotImplementedException();
        }

        public IAsyncResult BeginReceivePrivate(Scheduler.SVC.Message msg, Scheduler.SVC.Client receiver, AsyncCallback callback, object asyncState)
        {
            throw new NotImplementedException();
        }

        public void EndReceivePrivate(IAsyncResult result)
        {
            throw new NotImplementedException();
        }

        public IAsyncResult BeginReceive(Scheduler.SVC.Message msg, AsyncCallback callback, object asyncState)
        {
            throw new NotImplementedException();
        }

        public void EndReceive(IAsyncResult result)
        {
            throw new NotImplementedException();
        }

        public IAsyncResult BeginRefreshClients(List<Scheduler.SVC.Client> clients, AsyncCallback callback, object asyncState)
        {
            throw new NotImplementedException();
        }

        public void EndRefreshClients(IAsyncResult result)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Quartz Jobs

        internal class SendAlarmCommand : MainWindow, IMyJob
        {
            public void Execute(JobExecutionContext context)
            {
                Console.WriteLine("In MyJob class : " + context.JobDetail.Name);
                Console.WriteLine(string.Format("Running Alarm Job - {0}", System.DateTime.Now.ToString("r")));

                JobDataMap dataMap = context.JobDetail.JobDataMap;

                Console.WriteLine("Client ID - " + dataMap.GetString("ClientID"));
                Console.WriteLine("Clock ID - " + dataMap.GetString("ClockID"));
                Console.WriteLine("Command - " + dataMap.GetString("Command"));

                string command = (dataMap.GetString("Command"));
                Send(command); //Function in MainWindow

            }
        }

        internal class TVGuideUpdate : IMyJob
        {
            string GuideDirectory = ConfigurationManager.AppSettings["GuideDirectory"];

            public void Execute(JobExecutionContext context)
            {
                JobDataMap dataMap = context.JobDetail.JobDataMap;

                string guideURL = dataMap.GetString("GuideURL");
                string fileName = "iceguide.xml";
                string destFile = System.IO.Path.Combine(GuideDirectory, fileName);

                Console.WriteLine(string.Format("Running TV Guide Update Job - {0}", System.DateTime.Now.ToString("r")));
                Console.WriteLine("Downloading TV Guide...");

                if (!System.IO.Directory.Exists(GuideDirectory))
                {
                    System.IO.Directory.CreateDirectory(GuideDirectory);
                }

                WebClient webClient = new WebClient();
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
                webClient.DownloadFileAsync(new Uri(guideURL), destFile);
            }

            public void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
            {
                Console.WriteLine("TV Guide download completed.");
            }
        }

        internal interface IMyJob : IJob
        {
        }

        #endregion Quartz Jobs

    }

    
}


大家好,
很抱歉造成延迟,我设法找到了一个简单的解决方案.
以防万一有人有类似的问题,我发现了一个非常类似的帖子...

http://stackoverflow.com/questions/4632827/从一个单独的文件访问一个类的 [
Hi Guys,
Sorry for the delay, I have managed to find a simplet solution.
Just incase anyone has a similar problem, i found a very similar post...

http://stackoverflow.com/questions/4632827/access-mainwindow-control-from-a-class-in-a-separate-file[^]

Kind Regards,
Alex.


这篇关于WPF-从内部类调用父函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆