Example #1
0
        public string Call()
        {
            string returnvalue = "";

            try
            {
                WebClient webcli = new WebClient();
                if (this.networkcredential != null)
                {
                    webcli.Credentials = networkcredential;
                }
                webcli.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
                webcli.Headers.Add(customheaders);
                if (this.method == "")
                {
                    returnvalue = webcli.DownloadString(this.webserviceurl);
                }
                else
                {
                    byte[] data          = Encoding.ASCII.GetBytes(this.putdata);
                    byte[] responsebytes = webcli.UploadData(this.webserviceurl, this.method, data);
                    returnvalue = Encoding.ASCII.GetString(responsebytes);
                }
            }
            catch (Exception ex)
            {
                HomeGenieService.LogEvent(Domains.HomeAutomation_HomeGenie_Automation, this.GetType().Name, ex.Message, "Exception.StackTrace", ex.StackTrace);
            }
            return(returnvalue);
        }
Example #2
0
        private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
        {
            var logEntry = new HomeGenie.Data.LogEntry()
            {
                Domain      = Domains.HomeAutomation_HomeGenie,
                Source      = "Trapper",
                Description = "Unhandled Exception",
                Property    = "Error.Exception",
                Value       = e.ExceptionObject.ToString()
            };

            try
            {
                // try broadcast first
                _homegenie.LogBroadcastEvent(
                    logEntry.Domain,
                    logEntry.Source,
                    logEntry.Description,
                    logEntry.Property,
                    logEntry.Value
                    );
            }
            catch
            {
                HomeGenieService.LogEvent(logEntry);
            }
        }
Example #3
0
 /// <summary>
 /// Call the web service url and returns the server response as binary data.
 /// </summary>
 /// <returns>Byte array containing the raw server response.</returns>
 public byte[] GetBytes()
 {
     byte[] responseBytes = null;
     lock (httpSyncLock)
         using (var webClient = new WebClient())
         {
             try
             {
                 if (this.networkCredential != null)
                 {
                     webClient.Credentials = networkCredential;
                 }
                 webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
                 responseBytes = webClient.DownloadData(this.webServiceUrl);
             }
             catch (Exception ex)
             {
                 HomeGenieService.LogEvent(
                     Domains.HomeAutomation_HomeGenie_Automation,
                     this.GetType().Name,
                     ex.Message,
                     "Exception.StackTrace",
                     ex.StackTrace
                     );
             }
             finally
             {
                 webClient.Dispose();
             }
         }
     return(responseBytes);
 }
Example #4
0
        private void logInterval_Elapsed(object sender, ElapsedEventArgs eventArgs)
        {
            var end     = DateTime.UtcNow;
            var modules = (TsList <Module>)homegenie.Modules; //.Clone();

            foreach (var module in modules)
            {
                foreach (var parameter in module.Properties)
                {
                    if (parameter.Statistics.Values.Count > 0)
                    {
                        var values = parameter.Statistics.Values.FindAll(sv => (sv.Timestamp.Ticks <= end.Ticks && sv.Timestamp.Ticks > parameter.Statistics.LastProcessedTimestap.Ticks));
                        if (values.Count > 0)
                        {
                            double average = (values.Sum(d => d.Value) / values.Count);
                            //
                            //TODO: check db file age/size for archiving old data
                            //
                            string dbName   = GetStatisticsDatabaseName();
                            var    fileInfo = new FileInfo(dbName);
                            if (fileInfo.Length > dbSizeLimit) // 5Mb limit for stats - temporary limitations to get rid of in the future
                            {
                                //ResetStatisticsDatabase();
                                // TODO: Test method below, then use that instead of rsetting whole database.
                                CleanOldValuesFromStatisticsDatabase();
                            }
                            //
                            try
                            {
                                var dbCommand = dbConnection.CreateCommand();
                                // "TimeStart","TimeEnd","Domain","Address","Parameter","AverageValue", "CustomData"
                                dbCommand.Parameters.Add(new SQLiteParameter("@timestart", DateTimeToSQLite(parameter.Statistics.LastProcessedTimestap)));
                                dbCommand.Parameters.Add(new SQLiteParameter("@timeend", DateTimeToSQLite(end)));
                                dbCommand.Parameters.Add(new SQLiteParameter("@domain", module.Domain));
                                dbCommand.Parameters.Add(new SQLiteParameter("@address", module.Address));
                                dbCommand.Parameters.Add(new SQLiteParameter("@parameter", parameter.Name));
                                dbCommand.Parameters.Add(new SQLiteParameter("@avgvalue", average.ToString(CultureInfo.InvariantCulture)));
                                dbCommand.Parameters.Add(new SQLiteParameter("@data", module.Name));
                                dbCommand.CommandText = "INSERT INTO ValuesHist VALUES (@timestart, @timeend, @domain, @address, @parameter, @avgvalue, @data)";
                                dbCommand.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                HomeGenieService.LogEvent(
                                    Domains.HomeAutomation_HomeGenie,
                                    "Service.StatisticsLogger",
                                    ex.Message,
                                    "Exception.StackTrace",
                                    ex.StackTrace
                                    );
                            }
                            //
                            parameter.Statistics.LastProcessedTimestap = end;
                            parameter.Statistics.Values.Clear();
                        }
                    }
                }
            }
        }
Example #5
0
 /// <summary>
 /// Execute a setup function once the program is enabled. It is meant to be used in the "Trigger Code Block" to configure program configuration fields, parameters and features.
 /// </summary>
 /// <param name="functionBlock">Function name or inline delegate.</param>
 /// <remarks />
 /// <example>
 /// Example:
 /// <code>
 ///  Program.Setup(()=>
 ///  {
 ///      Program.AddInputField(
 ///          "MaxLevel",
 ///          "40",
 ///          "Keep level below the following value");
 ///      Program.AddFeature(
 ///          "Dimmer",
 ///          "EnergyManagement.EnergySavingMode",
 ///          "Energy Saving Mode enabled light");
 ///  });
 /// </code>
 /// </example>
 public void Setup(Action functionBlock)
 {
     try
     {
         if (!this.initialized)
         {
             //
             if (programModule == null)
             {
                 RelocateProgramModule();
             }
             //
             // mark config options to determine unused ones
             if (programModule != null)
             {
                 foreach (var parameter in programModule.Properties)
                 {
                     if (parameter.Name.StartsWith("ConfigureOptions."))
                     {
                         parameter.Description = null;
                     }
                 }
             }
             //
             HomeGenieService.LogEvent(
                 myProgramDomain,
                 myProgramId.ToString(),
                 "Automation Program",
                 Properties.PROGRAM_STATUS,
                 "Setup"
                 );
             functionBlock();
             //
             // remove deprecated config options
             if (programModule != null)
             {
                 var parameterList = programModule.Properties.FindAll(mp => mp.Name.StartsWith("ConfigureOptions."));
                 foreach (var parameter in parameterList)
                 {
                     if (parameter.Name.StartsWith("ConfigureOptions.") && parameter.Description == null)
                     {
                         programModule.Properties.Remove(parameter);
                     }
                 }
             }
             this.initialized = true;
             //
             homegenie.modules_RefreshPrograms();
             homegenie.modules_RefreshVirtualModules();
         }
     }
     catch (Exception e)
     {
         //TODO: report error
         throw (new Exception(e.StackTrace));
     }
 }
Example #6
0
 private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
 {
     HomeGenieService.LogEvent(new HomeGenie.Data.LogEntry()
     {
         Domain      = Domains.HomeAutomation_HomeGenie,
         Source      = "UnhandledExceptionTrapper",
         Description = e.ExceptionObject.ToString(),
         Property    = "HomeGenie.UnhandledException",
         Value       = e.ExceptionObject.ToString()
     });
 }
Example #7
0
        private void logInterval_Elapsed(object sender, ElapsedEventArgs eventArgs)
        {
            var end     = DateTime.UtcNow;
            var modules = (TsList <Module>)homegenie.Modules; //.Clone();

            foreach (var module in modules)
            {
                foreach (var parameter in module.Properties)
                {
                    // enntry counter
                    if (parameter.Statistics.Values.Count > 0)
                    {
                        var values = parameter.Statistics.Values.FindAll(sv => (sv.Timestamp.Ticks <= end.Ticks && sv.Timestamp.Ticks > parameter.Statistics.LastProcessedTimestap.Ticks));
                        //
                        if (values.Count > 0)
                        {
                            double average = (values.Sum(d => d.Value) / values.Count);
                            //
                            //TODO: check db file age/size for archiving old data
                            //
                            string dbName   = GetStatisticsDatabaseName();
                            var    fileInfo = new FileInfo(dbName);
                            if (fileInfo.Length > dbSizeLimit) // 5Mb limit for stats - temporary limitations to get rid of in the future
                            {
                                ResetStatisticsDatabase();
                            }
                            //
                            try
                            {
                                var dbCommand = dbConnection.CreateCommand();
                                // "TimeStart","TimeEnd","Domain","Address","Parameter","AverageValue"
                                dbCommand.CommandText = "INSERT INTO ValuesHist VALUES ('" + DateTimeToSQLite(parameter.Statistics.LastProcessedTimestap) + "','" + DateTimeToSQLite(end) + "','" + module.Domain + "','" + module.Address + "','" + parameter.Name + "'," + average.ToString(System.Globalization.CultureInfo.InvariantCulture) + ")";
                                dbCommand.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                HomeGenieService.LogEvent(
                                    Domains.HomeAutomation_HomeGenie,
                                    "Service.StatisticsLogger",
                                    ex.Message,
                                    "Exception.StackTrace",
                                    ex.StackTrace
                                    );
                            }
                            //
                            parameter.Statistics.LastProcessedTimestap = end;
                            parameter.Statistics.Values.Clear();
                        }
                    }
                }
            }
        }
        private void _loginterval_Elapsed(object sender, ElapsedEventArgs e)
        {
            DateTime        logend  = DateTime.UtcNow;
            TsList <Module> modules = (TsList <Module>)_homegenie.Modules; //.Clone();

            foreach (Module m in modules)
            {
                foreach (ModuleParameter mp in m.Properties)
                {
                    // enntry counter
                    if (mp.Statistics.Values.Count > 0)
                    {
                        List <ValueStatistics.StatValue> values = mp.Statistics.Values.FindAll(sv => (sv.Timestamp.Ticks <= logend.Ticks && sv.Timestamp.Ticks > mp.Statistics.LastProcessedTimestap.Ticks));
                        //
                        if (values.Count > 0)
                        {
                            TimeSpan trange  = new TimeSpan(logend.Ticks - mp.Statistics.LastProcessedTimestap.Ticks);
                            double   average = (values.Sum(d => d.Value) / values.Count);
                            //
                            //TODO: check db file age/size for archiving old data
                            //
                            string   dbname = _getStatisticsDatabaseName();
                            FileInfo fi     = new FileInfo(dbname);
                            if (fi.Length > _dbsizelimit) // 5Mb limit for stats - temporary limitations to get rid of in the future
                            {
                                _resetStatisticsDatabase();
                            }
                            //
                            try
                            {
                                SQLiteCommand dbcmd = _dbconnection.CreateCommand();

                                // "TimeStart","TimeEnd","Domain","Address","Parameter","AverageValue"
                                dbcmd.CommandText = "INSERT INTO ValuesHist VALUES ('" + _dateTimeSQLite(mp.Statistics.LastProcessedTimestap) + "','" + _dateTimeSQLite(logend) + "','" + m.Domain + "','" + m.Address + "','" + mp.Name + "'," + average.ToString(System.Globalization.CultureInfo.InvariantCulture) + ")";
                                dbcmd.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                HomeGenieService.LogEvent(Domains.HomeAutomation_HomeGenie, "Service.StatisticsLogger", ex.Message, "Exception.StackTrace", ex.StackTrace);
                            }
                            //
                            mp.Statistics.LastProcessedTimestap = logend;
                            //Console.WriteLine("Average value: " + average);
                            //Console.WriteLine("Time range: " + trange.TotalSeconds);
                            mp.Statistics.Values.Clear();
                        }
                    }
                }
            }
        }
Example #9
0
 private void _relocateprogrammodule()
 {
     // force automation modules regeneration
     _homegenie._modules_refresh_programs();
     //
     try
     {
         _programmodule = _homegenie.Modules.Find(rm => rm.Domain == _myprogramdomain && rm.Address == _myprogramid.ToString());
     }
     catch (Exception ex)
     {
         HomeGenieService.LogEvent(_myprogramdomain, _myprogramid.ToString(), ex.Message, "Exception.StackTrace", ex.StackTrace);
     }
 }
Example #10
0
        private bool _checkinstance(HomeGenieService homegenieref)
        {
            lock (_instobj)
            {
                if (_program_appdomain == null)
                {
                    DateTime starttime = DateTime.Now;

                    bool success = false;

                    // Creating script app domain
                    _program_appdomain = AppDomain.CurrentDomain; //AppDomain.CreateDomain("HomeGenieScriptDomain-" + this.Address);


                    TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks - starttime.Ticks);


                    starttime = DateTime.Now;
                    _program_assembly_type = _scriptassembly.GetType("HomeGenie.Automation.Scripting.ScriptingInstance");
                    _program_assembly      = Activator.CreateInstance(_program_assembly_type);


                    TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks - starttime.Ticks);


                    MethodInfo miSetHost = _program_assembly_type.GetMethod("SetHost");
                    //
                    try
                    {
                        miSetHost.Invoke(_program_assembly, new object[2] {
                            homegenieref, this.Address
                        });
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        HomeGenieService.LogEvent(Domains.HomeAutomation_HomeGenie_Automation, this.Address.ToString(), ex.Message, "Exception.StackTrace", ex.StackTrace);
                    }
                    //
                    _program_method_run = _program_assembly_type.GetMethod("Run");
                    _program_method_evaluatecondition = _program_assembly_type.GetMethod("EvaluateCondition");
                    _program_method_reset             = _program_assembly_type.GetMethod("Reset");
                    //
                    return(success);
                }
            }
            return(true);
        }
Example #11
0
        internal static Thread RunAsyncTask(AsyncFunction functionBlock)
        {
            var asyncTask = new Thread(() =>
            {
                try
                {
                    functionBlock();
                }
                catch (Exception ex)
                {
                    HomeGenieService.LogEvent(Domains.HomeAutomation_HomeGenie, "Service.Utility.RunAsyncTask", ex.Message, "Exception.StackTrace", ex.StackTrace);
                }
            });

            asyncTask.Start();
            return(asyncTask);
        }
Example #12
0
        public static Thread RunAsyncTask(AsyncFunction fnblock)
        {
            Thread at = new Thread(new ThreadStart(() =>
            {
                try
                {
                    fnblock();
                }
                catch (Exception ex)
                {
                    HomeGenieService.LogEvent(Domains.HomeAutomation_HomeGenie, "Service.Utility.RunAsyncTask", ex.Message, "Exception.StackTrace", ex.StackTrace);
                }
            }));

            at.Start();
            return(at);
        }
Example #13
0
 public ProgramHelper RaiseEvent(ModuleHelper module, string parameter, string value, string description)
 {
     MIG.InterfacePropertyChangedAction mact = new MIG.InterfacePropertyChangedAction();
     mact.Domain     = module.Instance.Domain;
     mact.Path       = parameter;
     mact.Value      = value;
     mact.SourceId   = module.Instance.Address;
     mact.SourceType = "Virtual Module";
     try
     {
         _homegenie.SignalModulePropertyChange(this, module.Instance, mact);
     }
     catch (Exception ex)
     {
         HomeGenieService.LogEvent(_programmodule.Domain, _programmodule.Address, ex.Message, "Exception.StackTrace", ex.StackTrace);
     }
     return(this);
 }
Example #14
0
        /// <summary>
        /// Call the web service url.
        /// </summary>
        /// <returns>String containing the server response.</returns>
        public string Call()
        {
            string returnvalue = "";

            lock (httpSyncLock)
                using (var webClient = new WebClient())
                {
                    try
                    {
                        webClient.Encoding = Encoding.UTF8;
                        if (this.networkCredential != null)
                        {
                            webClient.Credentials = networkCredential;
                        }
                        webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
                        webClient.Headers.Add(customHeaders);
                        if (this.method == "")
                        {
                            returnvalue = webClient.DownloadString(this.webServiceUrl);
                        }
                        else
                        {
                            byte[] data          = Encoding.UTF8.GetBytes(this.putData);
                            byte[] responsebytes = webClient.UploadData(this.webServiceUrl, this.method, data);
                            returnvalue = Encoding.UTF8.GetString(responsebytes);
                        }
                    }
                    catch (Exception ex)
                    {
                        HomeGenieService.LogEvent(
                            Domains.HomeAutomation_HomeGenie_Automation,
                            this.GetType().Name,
                            ex.Message,
                            "Exception.StackTrace",
                            ex.StackTrace
                            );
                    }
                    finally
                    {
                        webClient.Dispose();
                    }
                }
            return(returnvalue);
        }
Example #15
0
        private bool CheckAppInstance()
        {
            bool success = false;

            if (programDomain != null)
            {
                success = true;
            }
            else
            {
                try
                {
                    // Creating app domain
                    programDomain = AppDomain.CurrentDomain;
                    //
                    assemblyType = appAssembly.GetType("HomeGenie.Automation.Scripting.ScriptingInstance");
                    assembly     = Activator.CreateInstance(assemblyType);
                    //
                    MethodInfo miSetHost = assemblyType.GetMethod("SetHost");
                    miSetHost.Invoke(assembly, new object[2] {
                        homegenie, this.Address
                    });
                    //
                    methodRun = assemblyType.GetMethod("Run");
                    methodEvaluateCondition = assemblyType.GetMethod("EvaluateCondition");
                    methodReset             = assemblyType.GetMethod("Reset");
                    //
                    success = true;
                }
                catch (Exception ex)
                {
                    HomeGenieService.LogEvent(
                        Domains.HomeAutomation_HomeGenie_Automation,
                        this.Address.ToString(),
                        ex.Message,
                        "Exception.StackTrace",
                        ex.StackTrace
                        );
                }
            }
            return(success);
        }
Example #16
0
 private void RelocateProgramModule()
 {
     // force automation modules regeneration
     homegenie.modules_RefreshPrograms();
     //
     try
     {
         programModule = homegenie.Modules.Find(rm => rm.Domain == myProgramDomain && rm.Address == myProgramId.ToString());
     }
     catch (Exception ex)
     {
         HomeGenieService.LogEvent(
             myProgramDomain,
             myProgramId.ToString(),
             ex.Message,
             "Exception.StackTrace",
             ex.StackTrace
             );
     }
 }
Example #17
0
        /// <summary>
        /// Removes older values to keep DB size within configured size limit.
        /// </summary>
        /// <param name="numberOfDays">Records older than this number of days are removed.</param>
        private void CleanOldValuesFromStatisticsDatabase(int numberOfDays)
        {
            if (numberOfDays > 0)
            {
                //lock (dbLock)
                {
                    var dbCommand = dbConnection.CreateCommand();
                    dbCommand.CommandText = "DELETE FROM ValuesHist WHERE TimeStart < DATEADD(dd,-" + numberOfDays + ",GETDATE());";
                    dbCommand.ExecuteNonQuery();
                    dbCommand.CommandText = "VACUUM";
                    dbCommand.ExecuteNonQuery();

                    HomeGenieService.LogEvent(
                        Domains.HomeAutomation_HomeGenie,
                        "Service.StatisticsLogger",
                        "Cleaned old values from database.",
                        "DayThreshold",
                        numberOfDays.ToString()
                        );
                }
            }
        }
Example #18
0
        /// <summary>
        /// Adds a "feature" field of type "checkbox" or "text" to the matching domain/type modules. This field will be showing in the module options popup and it will be bound to the given module parameter.
        /// This command should only appear inside a Program.Setup delegate.
        /// </summary>
        /// <returns>
        /// ProgramHelper.
        /// </returns>
        /// <param name='forDomains'>
        /// A string with comma separated list of domains of modules that will showing this input field. Use an empty string for all domains.
        /// </param>
        /// <param name='forModuleTypes'>
        /// A string with comma separated list of types of modules that will showing this input field.
        /// </param>
        /// <param name='parameterName'>
        /// Name of the module parameter associated to this input field.
        /// </param>
        /// <param name='description'>
        /// Description for this input field.
        /// </param>
        public ProgramHelper AddFeature(
            string forDomains,
            string forModuleTypes,
            string parameterName,
            string description,
            string type
            )
        {
            var            program = homegenie.ProgramEngine.Programs.Find(p => p.Address.ToString() == myProgramId.ToString());
            ProgramFeature feature = null;

            //
            try
            {
                feature = program.Features.Find(f => f.Property == parameterName);
            }
            catch (Exception ex)
            {
                HomeGenieService.LogEvent(
                    myProgramDomain,
                    myProgramId.ToString(),
                    ex.Message,
                    "Exception.StackTrace",
                    ex.StackTrace
                    );
            }
            //
            if (feature == null)
            {
                feature = new ProgramFeature();
                program.Features.Add(feature);
            }
            feature.FieldType   = type;
            feature.Property    = parameterName;
            feature.Description = description;
            feature.ForDomains  = forDomains;
            feature.ForTypes    = forModuleTypes;
            return(this);
        }
Example #19
0
        /// <summary>
        /// Return the ProgramFeature object associated to the specified module parameter.
        /// </summary>
        /// <param name="propertyName">Parameter name.</param>
        public ProgramFeature Feature(string parameterName)
        {
            var            program = homegenie.ProgramEngine.Programs.Find(p => p.Address.ToString() == myProgramId.ToString());
            ProgramFeature feature = null;

            //
            try
            {
                feature = program.Features.Find(f => f.Property == parameterName);
            }
            catch (Exception ex)
            {
                HomeGenieService.LogEvent(
                    myProgramDomain,
                    myProgramId.ToString(),
                    ex.Message,
                    "Exception.StackTrace",
                    ex.StackTrace
                    );
            }
            //
            return(feature);
        }
Example #20
0
 /// <summary>
 /// Raise a parameter event and set the parameter with the specified value.
 /// </summary>
 /// <returns>ProgramHelper.</returns>
 /// <param name="parameter">Parameter name.</param>
 /// <param name="value">The new parameter value to set.</param>
 /// <param name="description">Event description.</param>
 public ProgramHelper RaiseEvent(string parameter, string value, string description)
 {
     try
     {
         var actionEvent = new MIG.InterfacePropertyChangedAction();
         actionEvent.Domain     = programModule.Domain;
         actionEvent.Path       = parameter;
         actionEvent.Value      = value;
         actionEvent.SourceId   = programModule.Address;
         actionEvent.SourceType = "Automation Program";
         homegenie.SignalModulePropertyChange(this, programModule, actionEvent);
     }
     catch (Exception ex)
     {
         HomeGenieService.LogEvent(
             programModule.Domain,
             programModule.Address,
             ex.Message,
             "Exception.StackTrace",
             ex.StackTrace
             );
     }
     return(this);
 }
Example #21
0
 /// <summary>
 /// Sends an E-Mail.
 /// </summary>
 /// <returns><c>true</c>, if message was sent, <c>false</c> otherwise.</returns>
 /// <param name="from">Message sender.</param>
 /// <param name="recipients">Message recipients.</param>
 /// <param name="subject">Message subject.</param>
 /// <param name="messageText">Message text.</param>
 public bool SendMessage(string from, string recipients, string subject, string messageText)
 {
     try
     {
         this.mailFrom = from;
         //this.mailTo = recipients;
         this.mailSubject = subject;
         this.mailBody    = messageText;
         //
         using (var message = new System.Net.Mail.MailMessage())
         {
             string[] mailRecipients = recipients.Split(';');
             for (int e = 0; e < mailRecipients.Length; e++)
             {
                 message.To.Add(mailRecipients[e]);
             }
             message.Subject = this.mailSubject;
             message.From    = new MailAddress(this.mailFrom);
             message.Body    = this.mailBody;
             //
             for (int a = 0; a < attachments.Count; a++)
             {
                 var attachment = new Attachment(
                     new MemoryStream(attachments.ElementAt(a).Value),
                     attachments.ElementAt(a).Key
                     );
                 message.Attachments.Add(attachment);
             }
             //
             if (this.mailService == "")
             {
                 // this is a System Parameter
                 var spSmtpServer = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                 {
                     return(mp.Name == "Messaging.Email.SmtpServer");
                 });
                 if (spSmtpServer != null)
                 {
                     this.mailService = spSmtpServer.Value;
                 }
             }
             if (this.mailPort == -1)
             {
                 // this is a System Parameter
                 var spSmtpPort = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                 {
                     return(mp.Name == "Messaging.Email.SmtpPort");
                 });
                 if (spSmtpPort != null && spSmtpPort.DecimalValue > 0)
                 {
                     this.mailPort = (int)spSmtpPort.DecimalValue;
                 }
             }
             if (this.mailSsl == -1)
             {
                 // this is a System Parameter
                 var spSmtpUseSsl = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                 {
                     return(mp.Name == "Messaging.Email.SmtpUseSsl");
                 });
                 if (spSmtpUseSsl != null && spSmtpUseSsl.Value.ToLower() == "true")
                 {
                     this.mailSsl = 1;
                 }
             }
             if (this.networkCredential == null)
             {
                 var username = "";
                 // this is a System Parameter
                 var spSmtpUserName = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                 {
                     return(mp.Name == "Messaging.Email.SmtpUserName");
                 });
                 if (spSmtpUserName != null)
                 {
                     username = spSmtpUserName.Value;
                 }
                 if (username != "")
                 {
                     var password = "";
                     // this is a System Parameter
                     var spSmtpPassword = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                     {
                         return(mp.Name == "Messaging.Email.SmtpPassword");
                     });
                     if (spSmtpPassword != null)
                     {
                         password = spSmtpPassword.Value;
                     }
                     this.networkCredential = new NetworkCredential(username, password);
                 }
             }
             //
             using (var smtpClient = new SmtpClient(this.mailService))
             {
                 smtpClient.Credentials = this.networkCredential;
                 if (this.mailPort > 0)
                 {
                     smtpClient.Port = this.mailPort;
                 }
                 if (this.mailSsl > 0)
                 {
                     smtpClient.EnableSsl = (this.mailSsl == 1);
                 }
                 smtpClient.Send(message);
                 smtpClient.Dispose();
                 //
                 attachments.Clear();
             }
         }
     }
     catch (Exception ex)
     {
         HomeGenieService.LogEvent(
             Domains.HomeAutomation_HomeGenie_Automation,
             this.GetType().Name,
             ex.Message,
             "Exception.StackTrace",
             ex.StackTrace
             );
         return(false);
     }
     return(true);
 }
Example #22
0
 public bool SendMessage(string from, string recipients, string subject, string messagetext)
 {
     try
     {
         this.mailfrom    = from;
         this.mailto      = recipients;
         this.mailsubject = subject;
         this.mailbody    = messagetext;
         //
         MailMessage message = new System.Net.Mail.MailMessage();
         string[]    tomails = recipients.Split(';');
         for (int e = 0; e < tomails.Length; e++)
         {
             message.To.Add(tomails[e]);
         }
         message.Subject = this.mailsubject;
         message.From    = new MailAddress(this.mailfrom);
         message.Body    = this.mailbody;
         //
         for (int a = 0; a < attachments.Count; a++)
         {
             Attachment att = new Attachment(new MemoryStream(attachments.ElementAt(a).Value), attachments.ElementAt(a).Key);
             message.Attachments.Add(att);
         }
         //
         if (this.mailservice == "")
         {
             ModuleParameter systemparam = _homegenie.Parameters.Find(delegate(ModuleParameter mp) { return(mp.Name == "Messaging.Email.SmtpServer"); });
             if (systemparam != null)
             {
                 this.mailservice = systemparam.Value;
             }
         }
         if (this.mailport == -1)
         {
             ModuleParameter systemparam = _homegenie.Parameters.Find(delegate(ModuleParameter mp) { return(mp.Name == "Messaging.Email.SmtpPort"); });
             if (systemparam != null && systemparam.DecimalValue > 0)
             {
                 this.mailport = (int)systemparam.DecimalValue;
             }
         }
         if (this.mailssl == -1)
         {
             ModuleParameter systemparam = _homegenie.Parameters.Find(delegate(ModuleParameter mp) { return(mp.Name == "Messaging.Email.SmtpUseSsl"); });
             if (systemparam != null && systemparam.Value.ToLower() == "true")
             {
                 this.mailssl = 1;
             }
         }
         if (this.networkcredential == null)
         {
             var             username    = "";
             ModuleParameter systemparam = _homegenie.Parameters.Find(delegate(ModuleParameter mp) { return(mp.Name == "Messaging.Email.SmtpUserName"); });
             if (systemparam != null)
             {
                 username = systemparam.Value;
             }
             if (username != "")
             {
                 var password = "";
                 systemparam = _homegenie.Parameters.Find(delegate(ModuleParameter mp) { return(mp.Name == "Messaging.Email.SmtpPassword"); });
                 if (systemparam != null)
                 {
                     password = systemparam.Value;
                 }
                 this.networkcredential = new NetworkCredential(username, password);
             }
         }
         //
         SmtpClient smtp = new SmtpClient(this.mailservice);
         smtp.Credentials = this.networkcredential;
         if (this.mailport > 0)
         {
             smtp.Port = this.mailport;
         }
         if (this.mailssl > 0)
         {
             smtp.EnableSsl = (this.mailssl == 1);
         }
         smtp.Send(message);
         smtp.Dispose();
         //
         attachments.Clear();
     }
     catch (Exception ex)
     {
         HomeGenieService.LogEvent(Domains.HomeAutomation_HomeGenie_Automation, this.GetType().Name, ex.Message, "Exception.StackTrace", ex.StackTrace);
         Console.WriteLine("Net.SendMail ERROR: " + ex.Message + "\n" + ex.StackTrace);
         return(false);
     }
     return(true);
 }