Exemplo n.º 1
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            //Gets the mail-addresses with googlemail.com or gmail.com
            foreach (MailAddressEntryObject recipient in _recipientsEntry)
            {
                if (recipient.Address.Address.EndsWith("@gmail.com") ||
                    recipient.Address.Address.EndsWith("@googlemail.com"))
                {
                    _recipients.Add(recipient.Address.Address);
                }
            }
            string to = String.Join(",", _recipients.ToArray());

            //TODO Fetching Longitude and Latitude!
            Dictionary<String, String> geoCode =
                Helpers.GetGeocodes(operation.Einsatzort.Location + " " + operation.Einsatzort.Street + " " + operation.Einsatzort.StreetNumber);
            String longitude = "0";
            String latitude = "0";
            if (geoCode != null)
            {
                longitude = geoCode[Resources.LONGITUDE];
                latitude = geoCode[Resources.LATITUDE];
            }
            String body = operation.ToString(SettingsManager.Instance.GetSetting("eAlarm", "text").GetString());
            String header = operation.ToString(SettingsManager.Instance.GetSetting("eAlarm", "header").GetString());
            var postParameters = new Dictionary<string, string>
                                     {
                                         {"email", to},
                                         {"header", header},
                                         {"text", body},
                                         {"long", longitude},
                                         {"lat", latitude}
                                     };
            string postData = postParameters.Keys.Aggregate("",
                                                            (current, key) =>
                                                            current +
                                                            (HttpUtility.UrlEncode(key) + "=" +
                                                             HttpUtility.UrlEncode(postParameters[key]) + "&"));

            byte[] data = Encoding.UTF8.GetBytes(postData);
            webRequest.ContentLength = data.Length;

            Stream requestStream = webRequest.GetRequestStream();
            var webResponse = (HttpWebResponse)webRequest.GetResponse();
            Stream responseStream = webResponse.GetResponseStream();

            requestStream.Write(data, 0, data.Length);
            requestStream.Close();

            if (responseStream != null)
            {
                var reader = new StreamReader(responseStream, Encoding.Default);
                string pageContent = reader.ReadToEnd();
                reader.Close();
                responseStream.Close();
                webResponse.Close();

                //TODO Analyzing Response
            }
        }
 private void ExportCustomTextFile(Operation operation)
 {
     using (StreamWriter sw = new StreamWriter(_configuration.CustomTextDestinationFileName, false, Encoding.UTF8))
     {
         sw.Write(operation.ToString(_configuration.CustomTextFormat));
     }
 }
Exemplo n.º 3
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            string header = _settings.GetSetting(SettingKeysJob.Header).GetValue<string>();

            string expression = _settings.GetSetting(SettingKeysJob.MessageContent).GetValue<string>();
            string message = operation.ToString(expression);

            Task.Factory.StartNew(() => SendToProwl(operation, message, header));
            Task.Factory.StartNew(() => SendToNotifyMyAndroid(operation, message, header));
        }
Exemplo n.º 4
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            IList<MobilePhoneEntryObject> recipients = GetRecipients(operation);
            if (recipients.Count == 0)
            {
                Logger.Instance.LogFormat(LogType.Info, this, Properties.Resources.NoRecipientsErrorMessage);
                return;
            }

            string format = _settings.GetSetting("SMSJob", "MessageFormat").GetValue<string>();
            string text = operation.ToString(format);
            text = text.Replace("Ö", "Oe").Replace("Ä", "Ae").Replace("Ü", "Ue").Replace("ö", "oe").Replace("ä", "ae").Replace("ü", "ue").Replace("ß", "ss");
            // Truncate the string if it is too long
            text = text.Truncate(160, true, true);

            // Invoke the provider-send asynchronous because it is a web request and may take a while
            _provider.Send(_userName, _password, recipients.Select(r => r.PhoneNumber), text);
        }
Exemplo n.º 5
0
        private void SendMail(Operation operation, IJobContext context)
        {
            using (MailMessage message = new MailMessage())
            {
                IList<MailAddressEntryObject> recipients = GetMailRecipients(operation);
                if (recipients.Count == 0)
                {
                    Logger.Instance.LogFormat(LogType.Info, this, Properties.Resources.NoRecipientsMessage);
                    return;
                }

                message.From = _senderEmail;
                foreach (MailAddressEntryObject recipient in recipients)
                {
                    switch (recipient.Type)
                    {
                        case MailAddressEntryObject.ReceiptType.CC: message.CC.Add(recipient.Address); break;
                        case MailAddressEntryObject.ReceiptType.Bcc: message.Bcc.Add(recipient.Address); break;
                        default:
                        case MailAddressEntryObject.ReceiptType.To: message.To.Add(recipient.Address); break;
                    }
                }

                try
                {
                    message.Subject = operation.ToString(_mailSubject, ObjectFormatterOptions.RemoveNewlines, null);
                    message.Body = operation.ToString(_mailBodyFormat);

                    message.BodyEncoding = Encoding.UTF8;
                    message.Priority = MailPriority.High;
                    message.IsBodyHtml = false;

                    if (_attachImage)
                    {
                        Attachment attachment = null;
                        if (context.Parameters.Keys.Contains("ImagePath"))
                        {
                            string imagePath = (string)context.Parameters["ImagePath"];
                            if (!string.IsNullOrWhiteSpace(imagePath))
                            {
                                if (File.Exists(imagePath))
                                {
                                    string[] convertTiffToJpeg = Helpers.ConvertTiffToJpeg(imagePath);
                                    Stream stream = Helpers.CombineBitmap(convertTiffToJpeg).ToStream(ImageFormat.Jpeg);
                                    attachment = new Attachment(stream, "fax.jpg");
                                    foreach (string s in convertTiffToJpeg)
                                    {
                                        File.Delete(s);
                                    }
                                }
                            }
                        }
                        if (attachment != null)
                        {
                            message.Attachments.Add(attachment);
                        }
                    }

                    _smptClient.Send(message);
                }
                catch (Exception ex)
                {
                    SmtpException smtpException = ex as SmtpException;
                    if (smtpException != null)
                    {
                        Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.SendExceptionSMTPMessage, smtpException.StatusCode, smtpException.Message);
                    }
                    else
                    {
                        Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.SendExceptionMessage);
                    }
                    Logger.Instance.LogException(this, ex);
                }
            }
        }
Exemplo n.º 6
0
 // try to insert a dict<str,obj> into table store
 // if conflict, try to merge or update
 public static TableStorageListDictResponse DictObjToTableStore(Operation operation, Dictionary<string, object> dict, string table, string partkey, string rowkey)
 {
     TableStorage ts = MakeDefaultTableStorage();
     var entity = new Dictionary<string, object>();
     entity.Add("PartitionKey", partkey);
     entity.Add("RowKey", rowkey);
     foreach (var key in dict.Keys)
         if (key != "PartitionKey" && key != "RowKey")
             entity.Add(key, dict[key]);
     var response = ts.InsertEntity(table, entity);
     if (response.http_response.status != HttpStatusCode.Created)
     {
         switch (operation)
         {
             case Operation.update:
                 response = ts.UpdateEntity(table, partkey, rowkey, entity);
                 break;
             case Operation.merge:
                 response = ts.MergeEntity(table, partkey, rowkey, entity);
                 break;
             default:
                 GenUtils.LogMsg("info", "DictToTableStore unexpected operation", operation.ToString());
                 break;
         }
         if (response.http_response.status != HttpStatusCode.NoContent)
         {
             GenUtils.PriorityLogMsg("error", "DictToTableStore: " + operation, response.http_response.status.ToString() + ", " + response.http_response.message);
         }
     }
     return response;
 }
Exemplo n.º 7
0
 private void NotifyMyAndroid(Operation operation)
 {
     string content = operation.ToString(_expression);
     List<String> nmaRecipients = (from pushEntryObject in GetRecipients(operation) where pushEntryObject.Consumer == "NMA" select pushEntryObject.RecipientApiKey).ToList();
     if (nmaRecipients.Count != 0)
     {
         try
         {
             NMA.Notify(nmaRecipients, ApplicationName, HeaderText, content, NMANotificationPriority.Emergency);
         }
         catch (Exception ex)
         {
             Logger.Instance.LogFormat(LogType.Error, this, Resources.ErrorNMA, ex.Message);
             Logger.Instance.LogException(this, ex);
         }
     }
 }
        public static void PerformanceTest(Operation operation)
        {
            Console.WriteLine("*****" + operation.ToString().ToUpper() + "*****");

            int resultInt = IntegerValue;
            StopWatch.Start();

            for (int i = 0; i < OperationCount; i++)
            {
                switch (operation)
                {
                    case Operation.Add:
                        resultInt += IntegerValue;
                        break;
                    case Operation.Substract:
                        resultInt -= IntegerValue;
                        break;
                    case Operation.Multiply:
                        resultInt *= IntegerValue;
                        break;
                    case Operation.Divide:
                        resultInt /= IntegerValue;
                        break;
                    default:
                        throw new InvalidOperationException("Invalid operation!");
                }
            }

            StopWatch.Stop();
            Console.WriteLine("{0,-20}:{1}", "Int", StopWatch.Elapsed);
            StopWatch.Reset();

            long resultLong = LongValue;
            StopWatch.Start();

            for (int i = 0; i < OperationCount; i++)
            {
                switch (operation)
                {
                    case Operation.Add:
                        resultLong += LongValue;
                        break;
                    case Operation.Substract:
                        resultLong -= LongValue;
                        break;
                    case Operation.Multiply:
                        resultLong *= LongValue;
                        break;
                    case Operation.Divide:
                        resultLong /= LongValue;
                        break;
                    default:
                        throw new InvalidOperationException("Invalid operation!");
                }
            }

            StopWatch.Stop();
            Console.WriteLine("{0,-20}:{1}", "Long", StopWatch.Elapsed);
            StopWatch.Reset();

            float resultFloat = FloatValue;
            StopWatch.Start();

            for (int i = 0; i < OperationCount; i++)
            {
                switch (operation)
                {
                    case Operation.Add:
                        resultFloat += FloatValue;
                        break;
                    case Operation.Substract:
                        resultFloat -= FloatValue;
                        break;
                    case Operation.Multiply:
                        resultFloat *= FloatValue;
                        break;
                    case Operation.Divide:
                        resultFloat /= FloatValue;
                        break;
                    default:
                        throw new InvalidOperationException("Invalid operation!");
                }
            }

            StopWatch.Stop();
            Console.WriteLine("{0,-20}:{1}", "Float", StopWatch.Elapsed);
            StopWatch.Reset();

            double resultDouble = DoubleValue;
            StopWatch.Start();

            for (int i = 0; i < OperationCount; i++)
            {
                switch (operation)
                {
                    case Operation.Add:
                        resultDouble += DoubleValue;
                        break;
                    case Operation.Substract:
                        resultDouble -= DoubleValue;
                        break;
                    case Operation.Multiply:
                        resultDouble *= DoubleValue;
                        break;
                    case Operation.Divide:
                        resultDouble /= DoubleValue;
                        break;
                    default:
                        throw new InvalidOperationException("Invalid operation!");
                }
            }

            StopWatch.Stop();
            Console.WriteLine("{0,-20}:{1}", "Double", StopWatch.Elapsed);
            StopWatch.Reset();

            decimal resultDecimle = DecimalValue;
            StopWatch.Start();

            for (int i = 0; i < OperationCount; i++)
            {
                switch (operation)
                {
                    case Operation.Add:
                        resultDecimle += DecimalValue;
                        break;
                    case Operation.Substract:
                        resultDecimle -= DecimalValue;
                        break;
                    case Operation.Multiply:
                        resultDecimle *= DecimalValue;
                        break;
                    case Operation.Divide:
                        resultDecimle /= DecimalValue;
                        break;
                    default:
                        throw new InvalidOperationException("Invalid operation!");
                }
            }

            StopWatch.Stop();
            Console.WriteLine("{0,-20}:{1}", "Decimal", StopWatch.Elapsed);
            StopWatch.Reset();
        }
 //protected virtual void FormatPrefix(StringBuilder sb, Prefixes prefix)
 //{
 //    sb.Append((prefix & Prefixes.Group1).ToString());
 //}
 public virtual string FormatMnemonic(Operation operation)
 {
     return operation.ToString().ToLowerInvariant();
 }
Exemplo n.º 10
0
 public override string FormatMnemonic(Operation operation)
 {
     var attribute = operation.GetAttribute<DescriptionAttribute>();
     if (attribute != null)
     {
         string description = attribute.Description;
         return string.Format("<span title=\"{2}: {0}\">{1}</span>",
             attribute.Description.EscapeXml(),
             operation.ToString().ToLowerInvariant(),
             operation);
     }
     return base.FormatMnemonic(operation);
 }
Exemplo n.º 11
0
        private static List<URIish> getURIs(RemoteConfig cfg, Operation op)
        {
            switch (op)
            {
                case Operation.FETCH:
                    return cfg.URIs;

                case Operation.PUSH:
                    List<URIish> uris = cfg.PushURIs;
                    if (uris.Count == 0)
                    {
                        uris = cfg.URIs;
                    }
                    return uris;

                default:
                    throw new ArgumentException(op.ToString());
            }
        }
Exemplo n.º 12
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            string body = operation.ToString(_settings.GetSetting("eAlarm", "text").GetValue<string>());
            string header = operation.ToString(_settings.GetSetting("eAlarm", "header").GetValue<string>());
            string location = operation.Einsatzort.ToString();

            bool encryption = _settings.GetSetting("eAlarm", "Encryption").GetValue<bool>();
            if (encryption)
            {
                string encryptionKey = _settings.GetSetting("eAlarm", "EncryptionKey").GetValue<string>();

                body = Helper.Encrypt(body, encryptionKey);
                header = Helper.Encrypt(header, encryptionKey);
                location = Helper.Encrypt(location, encryptionKey);
            }

            string[] to = GetRecipients(operation).Where(pushEntryObject => pushEntryObject.Consumer == "eAlarm").Select(pushEntryObject => pushEntryObject.RecipientApiKey).ToArray();

            Content content = new Content()
            {
                registration_ids = to,
                data = new Content.Data()
               {
                   awf_title = header,
                   awf_message = body,
                   awf_location = location
               }
            };

            string message = new JavaScriptSerializer().Serialize(content);

            HttpStatusCode result = 0;
            if (!SendGcmNotification(ApiKey, message, ref result))
            {
                Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.ErrorSendingNotification, result);
            }
        }
Exemplo n.º 13
0
        private void drawResultEPBasedGraph(ref Chart chart, TrapezoidFuzzyNumber fnumA, TrapezoidFuzzyNumber fnumB, Operation operation, Color color)
        {
            // calculate result points list
            decimal xA, xB, xResult;
            decimal aProbability, bProbability, minProbability;
            CPoint tempPoint = null;
            List<CPoint> resultPointList = new List<CPoint>();
            xA = fnumA.BottomLeft;
            while (xA <= fnumA.BottomRight)
            {
                xB = fnumB.BottomLeft;
                while (xB <= fnumB.BottomRight)
                {
                    xResult = ExtensionPrinciple.Calculate(operation, xA, xB);
                    //if (operation == Operation.Mul || operation == Operation.Div)
                    xResult = Math.Round(xResult, numOfFracDigi);

                    aProbability = fnumA.Probability(xA);
                    bProbability = fnumB.Probability(xB);
                    minProbability = Math.Min(aProbability, bProbability);

                    tempPoint = resultPointList.FirstOrDefault(p => p.x == xResult);
                    if (tempPoint == null)
                    {
                        resultPointList.Add(new CPoint(xResult, minProbability));
                    }
                    else
                    {
                        tempPoint.y = Math.Max(tempPoint.y, minProbability);
                    }

                    xB += smooth;
                }

                xA += smooth;
            }

            // chart by line
            Series seriesLine = chart.Series.Add(operation.ToString());
            seriesLine.ChartType = SeriesChartType.Line;
            seriesLine.BorderWidth = 2;
            seriesLine.Color = color;
            // chart by point
            Series seriesPoint = chart.Series.Add(operation.ToString() + "_point");
            seriesPoint.ChartType = SeriesChartType.Point;
            seriesPoint.BorderWidth = 2;
            seriesPoint.Color = color;
            seriesPoint.IsVisibleInLegend = false;

            // draw the graph
            foreach (CPoint p in resultPointList.OrderBy(i => i.x))
            {
                // by line
                if (checkBoxDrawLine.Checked)
                    seriesLine.Points.AddXY(p.x, p.y);
                // by point
                seriesPoint.Points.AddXY(p.x, p.y);
            }

            addLog(operation.ToString() + " num of point :" + resultPointList.Count.ToString());
            resultPointList.Clear();
        }
Exemplo n.º 14
0
        private void drawResultIntervalBasedGraph(ref Chart chart, TrapezoidFuzzyNumber fnumA, TrapezoidFuzzyNumber fnumB, Operation operation, Color color)
        {
            // calculate result points list
            decimal y = 0;
            Interval acut, a, b;
            List<CPoint> resultPointListLeft = new List<CPoint>();
            List<CPoint> resultPointListRight = new List<CPoint>();
            while (y <= 1)
            {
                a = fnumA.AlphaCut(y);
                b = fnumB.AlphaCut(y);
                acut = ArithmeticInterval.Calculate(operation, a, b);

                resultPointListLeft.Add(new CPoint(acut.LowerBound, y));
                resultPointListRight.Add(new CPoint(acut.UpperBound, y));
                y += smooth;
            }

            y = 1;
            a = fnumA.AlphaCut(y);
            b = fnumB.AlphaCut(y);
            acut = ArithmeticInterval.Calculate(operation, a, b);
            decimal x = acut.LowerBound;
            while (x <= acut.UpperBound)
            {
                resultPointListLeft.Add(new CPoint(x, y));
                x += smooth;
            }

            // chart by line
            Series seriesLine = chart.Series.Add(operation.ToString());
            seriesLine.ChartType = SeriesChartType.Line;
            seriesLine.BorderWidth = 2;
            seriesLine.Color = color;
            // chart by point
            Series seriesPoint = chart.Series.Add(operation.ToString() + "_point");
            seriesPoint.ChartType = SeriesChartType.Point;
            seriesPoint.BorderWidth = 2;
            seriesPoint.Color = color;
            seriesPoint.IsVisibleInLegend = false;

            // draw the graph
            foreach (CPoint p in resultPointListLeft.OrderBy(i => i.x).OrderBy(i => i.y))
            {
                // by line
                if (checkBoxDrawLine.Checked)
                    seriesLine.Points.AddXY(p.x, p.y);
                // by point
                seriesPoint.Points.AddXY(p.x, p.y);
            }
            foreach (CPoint p in resultPointListRight.OrderBy(i => i.x).OrderByDescending(i => i.y))
            {
                // by line
                if (checkBoxDrawLine.Checked)
                    seriesLine.Points.AddXY(p.x, p.y);
                // by point
                seriesPoint.Points.AddXY(p.x, p.y);
            }

            addLog(operation.ToString() + " num of point :" + (resultPointListLeft.Count + resultPointListRight.Count).ToString());
            resultPointListLeft.Clear();
            resultPointListRight.Clear();
        }
Exemplo n.º 15
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            string body = operation.ToString(_settings.GetSetting("eAlarm", "text").GetValue<string>());
            string header = operation.ToString(_settings.GetSetting("eAlarm", "header").GetValue<string>());
            string location = operation.Einsatzort.ToString();
            bool encryption = _settings.GetSetting("eAlarm", "Encryption").GetValue<bool>();
            string encryptionKey = _settings.GetSetting("eAlarm", "EncryptionKey").GetValue<string>();
            if (encryption)
            {
                body = Helper.Encrypt(body, encryptionKey);
                header = Helper.Encrypt(header, encryptionKey);
                location = Helper.Encrypt(location, encryptionKey);
            }

            string[] to = GetRecipients(operation).Where(pushEntryObject => pushEntryObject.Consumer == "eAlarm").Select(pushEntryObject => pushEntryObject.RecipientApiKey).ToArray();

            Content content = new Content()
            {
                registration_ids = to,
                data = new Content.Data()
                    {
                        awf_title = header,
                        awf_message = body,
                        awf_location = location
                    }
            };
            string message = new JavaScriptSerializer().Serialize(content);

            HttpStatusCode result = 0;
            if (SendGCMNotification("AIzaSyA5hhPTlYxJsEDniEoW8OgfxWyiUBEPiS0", message, ref result))
            {
                Logger.Instance.LogFormat(LogType.Info, this, "Succesfully sent eAlarm notification");
            }
            else
            {
                Logger.Instance.LogFormat(LogType.Error, this, "Error while sending eAlarm notification Errorcode: '{0}'", (int)result);
            }
        }
Exemplo n.º 16
0
Arquivo: Global.cs Projeto: m12k/Files
        public static bool IsCodeExist(string originalValue, string currentValue, string table, string field, Operation operation)
        {
            try 
	        {	
                BTSSContext ctx = new BTSSContext(ConnectionString);
     
                return ctx.IsCodeExist(originalValue,currentValue,table,field,operation.ToString()).FirstOrDefault().IsExist.Value;                 
	        }
	        catch (Exception)
	        { 
		    throw;
	        }
        }
Exemplo n.º 17
0
        private void Execute(Operation operation)
        {
            IList<MobilePhoneEntryObject> recipients = GetRecipients(operation);
            if (recipients.Count == 0)
            {
                Logger.Instance.LogFormat(LogType.Info, this, Properties.Resources.NoRecipientsErrorMessage);
                return;
            }

            string format = _settings.GetSetting(SettingKeys.MessageFormat).GetValue<string>();
            string text = operation.ToString(format);
            text = ReplaceUmlauts(text);

            text = text.Truncate(SmsMessageMaxLength, true, true);

            string userName = _settings.GetSetting(SettingKeys.UserName).GetValue<string>();
            string password = _settings.GetSetting(SettingKeys.Password).GetValue<string>();

            try
            {
                _provider.Send(userName, password, recipients.Select(r => r.PhoneNumber), text);
            }
            catch (Exception ex)
            {
                Logger.Instance.LogException(this, ex);
                Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.SendSmsErrorMessage);
            }
        }
Exemplo n.º 18
0
        private void SendMail(Operation operation, IJobContext context)
        {
            using (MailMessage message = new MailMessage())
            {
                IList<MailAddressEntryObject> recipients = GetMailRecipients(operation);
                if (recipients.Count == 0)
                {
                    Logger.Instance.LogFormat(LogType.Info, this, Properties.Resources.NoRecipientsMessage);
                    return;
                }

                message.From = _senderEmail;
                foreach (MailAddressEntryObject recipient in recipients)
                {
                    switch (recipient.Type)
                    {
                        case MailAddressEntryObject.ReceiptType.CC: message.CC.Add(recipient.Address); break;
                        case MailAddressEntryObject.ReceiptType.Bcc: message.Bcc.Add(recipient.Address); break;
                        default:
                        case MailAddressEntryObject.ReceiptType.To: message.To.Add(recipient.Address); break;
                    }
                }

                try
                {
                    message.Subject = operation.ToString(_mailSubject, ObjectFormatterOptions.RemoveNewlines, null);
                    message.Body = operation.ToString(_mailBodyFormat);

                    message.BodyEncoding = Encoding.UTF8;
                    message.Priority = MailPriority.High;
                    message.IsBodyHtml = false;

                    if (_attachImage)
                    {
                        try
                        {
                            AttachImage(context, message);
                        }
                        catch (Exception ex)
                        {
                            Logger.Instance.LogException(this, ex);
                            Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.AttachImageFailed);
                        }
                    }

                    _smptClient.Send(message);
                }
                catch (Exception ex)
                {
                    SmtpException smtpException = ex as SmtpException;
                    if (smtpException != null)
                    {
                        Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.SendExceptionSMTPMessage, smtpException.StatusCode, smtpException.Message);
                    }
                    else
                    {
                        Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.SendExceptionMessage);
                    }
                    Logger.Instance.LogException(this, ex);
                }
            }
        }
Exemplo n.º 19
0
        // TODO: should be driven by playerstate here
        public void UpdateTrayMenu(Operation validOperation, bool isBgMusicVisible, bool isRunning, bool mixerVisible)
        {
            // Don't regenerate if state hasn't changed
            if ((validOperation == _validOperation) && (_isBgMusicVisible == isBgMusicVisible) && (_isRunning == isRunning) && (_mixerVisible == mixerVisible))
                return;

            _validOperation = validOperation;
            _isBgMusicVisible = isBgMusicVisible;
            _isRunning = isRunning;
            _mixerVisible = mixerVisible;

            ContextMenuStrip trayMenu = new ContextMenuStrip();
            trayMenu.Items.Add(validOperation.ToString(), null, OnValidOperation); // or mute/pause if already playing
            if (isRunning)
                trayMenu.Items.Add("Stop", null, OnStop);
            trayMenu.Items.Add("-", null, OnNothing);
            SoundPlayerInfo playerInfo = SmartVolManagerPackage.BgMusicManager.MuteFmConfig.GetActiveBgMusic();
            string playerName = (playerInfo != null) ? playerInfo.Name : "Player";
            if (playerName.Length > 20)
                playerName = playerName.Substring(0, 20).Trim() + "...";
            trayMenu.Items.Add("Show " + playerName, null, OnShow); // Show is always an option
            //            if (isBgMusicVisible) // TODO: used to also require isrunning here
            //                trayMenu.Items.Add("Hide " + playerName, null, OnHide);

            if (validOperation != Operation.Play)
            {
                if ((SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.NextSongCommand != "") || (SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.PrevSongCommand != "") || (SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.ShuffleCommand != "") || (SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.LikeCommand != "") || (SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.DislikeCommand != ""))
                    trayMenu.Items.Add("-", null, OnNothing);
                if (SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.NextSongCommand != "")
                    trayMenu.Items.Add("Next Track", null, OnNextTrack);
                if (SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.PrevSongCommand != "")
                    trayMenu.Items.Add("Prev Track", null, OnPrevTrack);
                if (SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.LikeCommand != "")
                    trayMenu.Items.Add("Like", null, OnLike);
                if (SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.DislikeCommand!= "")
                    trayMenu.Items.Add("Dislike", null, OnDislike);

                if (SmartVolManagerPackage.BgMusicManager.ActiveBgMusic.ShuffleCommand != "")
                    trayMenu.Items.Add("Shuffle", null, OnShuffle);
            }

            trayMenu.Items.Add("-", null, OnNothing);
            trayMenu.Items.Add("Show " + Constants.ProgramName, null, OnShowMixer);
            if (mixerVisible == true)
                trayMenu.Items.Add("Hide " + Constants.ProgramName, null, OnHideMixer);
            trayMenu.Items.Add("-", null, OnNothing);

            //            trayMenu.MenuItems.Add("Settings", OnSettings); //TODO: not implemented yet
            trayMenu.Items.Add("About", null, OnAbout);
            trayMenu.Items.Add("-", null, OnNothing);
            trayMenu.Items.Add("Exit", null, OnExit);

            _trayIcon.ContextMenuStrip = trayMenu;
            trayMenu.Opening += new CancelEventHandler(trayMenu_Opening);

            UiCommands.TrayLoaded = true; // TODO: shouldn't go here
        }