Example #1
0
        private void Button_Save_Click(object sender, RoutedEventArgs e)
        {
            WpfConfiguration config = ConfigContent.Content as WpfConfiguration;

            try
            {
                configuration.OnSave();
                module.OnSaved(config);
                ((ModuleBase)module).SetConfigString();
            }
            catch
            {
                ErrorLog.AddError(ErrorType.Failure, "Error saving " + configuration.Name);
            }

            ThreadPool.QueueUserWorkItem(o =>
            {
                try
                {
                    configuration.OnClosing();
                }
                catch
                {
                    Dispatcher.Invoke(DispatcherPriority.Normal, (System.Action)(() =>
                    {
                        ErrorLog.AddError(ErrorType.Failure, "Error closing " + configuration.Name + "'s configuration");
                    }));
                }
            });
            ((MainWindow)Application.Current.MainWindow).Save();
            DialogResult = true;
        }
Example #2
0
        protected override void OnEnabling(EnablingEventArgs e)
        {
            timer          = new Timer();
            timer.Interval = 100; // Setting the timer to 0.1 seconds so that it will get the initial list right away.
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

            isVisible  = false;
            wasVisible = false;
            isFirstRun = true;

            deviceAddress = null;

            try
            {
                bluetoothClient = new BluetoothClient();

                timer.Start();
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.BT_NoBluetooth);
                Logger.Write(ex);

                e.Cancel = true;
            }
        }
Example #3
0
        public string SaveImage(ref Bitmap image)
        {
            Bitmap tempImage = image;

            Logger.WriteLine("SaveImage");
            DateTime now      = DateTime.Now;
            string   filename = fileNamePrefix + "_" +
                                now.Year.ToString("D2") + "-" +
                                now.Month.ToString("D2") + "-" +
                                now.Day.ToString("D2") + "_" +
                                now.Hour.ToString("D2") + "-" +
                                now.Minute.ToString("D2") + "-" +
                                now.Second.ToString("D2") + ".jpg";
            string path = folderLocation + "\\" + filename;

            Logger.WriteLine("saving file to " + path);
            try
            {
                tempImage.Save(path, ImageFormat.Jpeg);
                ErrorLog.AddError(ErrorType.Message, "Picture saved to: " + path);
            }
            catch
            {
                Logger.WriteLine("Exception while saving picture");
                ErrorLog.AddError(ErrorType.Failure, "Could not save a picture to: " + path);
            }
            tempImage.Dispose();
            tempImage = null;
            return(path);
        }
Example #4
0
 public override void Perform()
 {
     try
     {
         System.Diagnostics.Process.Start(Url);
     }
     catch (Exception exc1)
     {
         // System.ComponentModel.Win32Exception is a known exception that occurs when Firefox is default browser.
         // It actually opens the browser but STILL throws this exception so we can just ignore it.  If not this exception,
         // then attempt to open the URL in IE instead.
         if (exc1.GetType() == typeof(System.ComponentModel.Win32Exception))
         {
             // sometimes throws exception so we have to just ignore
             // this is a common .NET bug that no one online really has a great reason for so now we just need to try to open
             // the URL using IE if we can.
             try
             {
                 var startInfo = new System.Diagnostics.ProcessStartInfo("IExplore.exe", Url);
                 System.Diagnostics.Process.Start(startInfo);
             }
             catch
             {
                 ErrorLog.AddError(ErrorType.Failure, Strings.OpenUrl_CouldntOpenUrl);
             }
         }
     }
 }
Example #5
0
        protected override void OnEnabling(EnablingEventArgs e)
        {
            base.OnEnabling(e);

            if (!e.Cancel)
            {
                try
                {
                    foreach (Video entry in currentVideoList)
                    {
                        if (lastVideoAddedTimestamp.CompareTo(entry.YouTubeEntry.Published) < 0)
                        {
                            lastVideoAddedTimestamp = entry.YouTubeEntry.Published;
                        }
                    }

                    StartTimer(int.Parse(Strings.General_TimeInterval));
                }
                catch (Exception ex)
                {
                    ErrorLog.AddError(ErrorType.Failure, string.Format(Strings.GooglePlus_ErrorMonitoringYouTubeUploadedVideos, username));
                    Logger.Write(ex);

                    e.Cancel = true;
                    return;
                }
            }
        }
Example #6
0
        protected override void OnEnabling(EnablingEventArgs e)
        {
            baseUrl = "http://gdata.youtube.com/feeds/api/videos/";
            lastCommentAddedTimestamp = DateTime.MinValue;

            // We need to check if the video exists.
            try
            {
                InitializeYoutubeConnection();

                Uri videoEntryUrl = new Uri(baseUrl + videoID);
                video = request.Retrieve <Video>(videoEntryUrl);
            }
            catch (GDataRequestException ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.YouTubeVideoDoesntExists);
                Logger.Write(ex);

                e.Cancel = true;
                return;
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.YouTube_ErrorMonitoringComment);
                Logger.Write(ex);

                e.Cancel = true;
                return;
            }

            isFirstTime = true;

            StartTimer(100);
        }
Example #7
0
        protected override void OnEnabling(EnablingEventArgs e)
        {
            lastVideoAddedTimestamp = DateTime.MinValue;

            try
            {
                InitializeYoutubeConnection();

                feedUri   = new Uri("http://gdata.youtube.com/feeds/api/users/" + username + "/uploads");
                videoFeed = request.Get <Video>(feedUri);

                currentVideoList = videoFeed.Entries.ToList();
            }
            catch (GDataRequestException ex)
            {
                ErrorLog.AddError(ErrorType.Failure, string.Format(Strings.General_Incorrect, Strings.General_ProfileID));
                Logger.Write(ex);

                e.Cancel = true;
                return;
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, string.Format(Strings.GooglePlus_ErrorMonitoringYouTubeUploadedVideos, username));
                Logger.Write(ex);

                e.Cancel = true;
                return;
            }
        }
Example #8
0
        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            WpfConfiguration config = ConfigContent.Content as WpfConfiguration;

            try
            {
                configuration.OnSave();
                SelectedModuleInstance.OnSaved(config);
                ((ModuleBase)SelectedModuleInstance).SetConfigString();
            }
            catch
            {
                ErrorLog.AddError(ErrorType.Failure, "Error saving " + SelectedModule.Name);
            }

            ThreadPool.QueueUserWorkItem(o =>
            {
                try
                {
                    configuration.OnClosing();
                }
                catch
                {
                    ErrorLog.AddError(ErrorType.Failure, "Error closing " + SelectedModule.Name + "'s configuration");
                }
            });
            DialogResult = true;
        }
Example #9
0
        protected override void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            timer.Stop();

            try
            {
                // Calling this method will return a list of the currently visible devices.
                // Note that this method takes up to 10 seconds to complete, in order to have accurate results.
                newDevices = bluetoothClient.DiscoverDevices(10, false, false, false, true).ToList();

                if (devices == null)
                {
                    // If it's the first time this event is triggered we get the list of the devices and we set the timer.
                    MakeFirstListOfDevices();
                }
                else
                {
                    if (FindNewDevices())
                    {
                        // If a new device is found we trigger this event.
                        Trigger();
                    }

                    RemoveNoLongerVisibleDevices();
                }
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.BT_ErrorMonitoringBluetooth);
                Logger.Write(ex);
            }

            timer.Start();
        }
Example #10
0
        /// <summary>
        /// This method will try to pair the computer with the bluetooth device indentified by it's address.
        /// </summary>
        public override void Perform()
        {
            try
            {
                device = new BluetoothDeviceInfo(BluetoothAddress.Parse(deviceAddressString));

                // Adding a warning message if the device is not in range.
                if (device == null)
                {
                    ErrorLog.AddError(ErrorType.Failure, string.Format(CultureInfo.CurrentCulture, Strings.BT_DeviceAddressNotFound, deviceAddressString));
                    return;
                }

                if (MakePairRequest())
                {
                    ErrorLog.AddError(ErrorType.Message, String.Format(Strings.BT_SuccessfulPairAddress, deviceAddressString));
                }
            }
            catch (PlatformNotSupportedException ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.BT_NoBluetooth);
                Logger.Write(ex);
            }
            catch (SocketException ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.BT_CantConnectToDevice);
                Logger.Write(ex);
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.BT_CantPairWithDevice);
                Logger.Write(ex);
            }
        }
Example #11
0
        /// <summary>
        /// Retrieve the stock price or delta (change in price)
        /// depending on what the user specified to watch for
        /// </summary>
        private void CheckStock(object sender, EventArgs e)
        {
            // Test for internet connection
            if (Utilities.ConnectedToInternet())
            {
                internetFlag = true;
                try
                {
                    // Retrieve XML document
                    string url = "http://www.google.com/ig/api?stock=" + stockSymbol;

                    WebRequest             webRequest    = WebRequest.Create(url);
                    HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                    webRequest.CachePolicy = noCachePolicy;

                    using (WebResponse webResponse = webRequest.GetResponse())
                    {
                        using (Stream responseStream = webResponse.GetResponseStream())
                        {
                            StreamReader s         = new StreamReader(responseStream, Encoding.GetEncoding(1252));
                            XmlReader    stockData = XmlReader.Create(s);

                            string readTo = changeParam ? "change" : "last";
                            stockData.ReadToFollowing(readTo);
                            double livePrice = Double.Parse(stockData.GetAttribute("data"));

                            // if the stock is above the watching price and user wants to trigger above
                            // OR
                            // if stock is below watching price and the user wants to trigger below
                            // stock price > 0 for all non-negative testing
                            if ((stockPrice > 0 && ((abovePrice && livePrice >= stockPrice) || (!abovePrice && livePrice <= stockPrice))) ||
                                ((abovePrice && livePrice <= stockPrice) || (!abovePrice && livePrice >= stockPrice)))
                            {
                                // logic for when to Trigger()
                                // trigger once when passed, then trigger again once barrier has been reset
                                // ELSE IF
                                // trigger on every pass AND the stock price is at a "reset point" enables ability to trigger on re-pass of point
                                if (!hasPassed)
                                {
                                    hasPassed = true;
                                    Trigger();
                                }
                                else if ((triggerEvery && (abovePrice && livePrice >= stockPrice + PriceOffset)) || (!abovePrice && livePrice <= stockPrice - PriceOffset))
                                {
                                    hasPassed = false;
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            else if (internetFlag)
            {
                internetFlag = false;
                ErrorLog.AddError(ErrorType.Warning, String.Format(Strings.Internet_NotConnected, "Stock"));
            }
        }
Example #12
0
        protected override void OnEnabling(EnablingEventArgs e)
        {
            devices    = null;
            auxDevices = null;
            newDevices = null;

            timer          = new Timer();
            timer.Interval = 100;
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

            try
            {
                bluetoothClient = new BluetoothClient();
                auxDevices      = new List <BluetoothDeviceInfo>();

                timer.Start();
            }
            catch (Exception ex)
            {
                // If the bluetooth capability is not available for this computer the event will not be enabled and an error message will be shown.
                ErrorLog.AddError(ErrorType.Failure, Strings.BT_NoBluetooth);
                Logger.Write(ex);

                e.Cancel = true;
            }
        }
Example #13
0
        protected override void OnEnabling(EnablingEventArgs e)
        {
            isFirstTime = true;

            try
            {
                apiHelper = new GooglePlusAPIHelper(profileId, Strings.GooglePlus_ApiKey);

                // Trying to get the current user information in order to see if the entered profileId exists.
                apiHelper.GetPerson();
            }
            catch (WebException ex)
            {
                ErrorLog.AddError(ErrorType.Failure, string.Format(Strings.General_Incorrect, Strings.General_ProfileID));
                Logger.Write(ex);

                e.Cancel = true;
                return;
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.GooglePlus_EventCouldntBeEnabled);
                Logger.Write(ex);

                e.Cancel = true;
                return;
            }
        }
Example #14
0
        /// <summary>
        /// If an instance of the Excel application exits this method will set it's CheckCompatibility property to true.
        /// </summary>
        public override void Perform()
        {
            try
            {
                app = (OExcel.Application)Marshal.GetActiveObject("Excel.Application");
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.Excel_ApplicationNotFound);
                Logger.Write(ex);

                return;
            }

            try
            {
                OExcel.Workbook workbook = app.ActiveWorkbook;

                if (workbook == null)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.Excel_NoActiveWorkbook);
                }
                else
                {
                    // When the workbook is saved, if it's not compatible, the compatibility window will be displayed
                    workbook.CheckCompatibility = true;
                }
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.Excel_CantCheckCompatibility);
                Logger.Write(ex);
            }
        }
Example #15
0
        public override void Perform()
        {
            bool isCallActive = false;

            try
            {
                if (VerifySkypeIDValidity(skypeID))
                {
                    foreach (Call call in skype.ActiveCalls)
                    {
                        if (call.PartnerHandle.Equals(skypeID))
                        {
                            isCallActive = true;
                            call.set_InputDevice(TCallIoDeviceType.callIoDeviceTypeFile, filePath);
                        }
                    }

                    if (isCallActive)
                    {
                        ErrorLog.AddError(ErrorType.Message, Strings.Successful_AudioMessage);
                    }
                    else
                    {
                        ErrorLog.AddError(ErrorType.Failure, string.Format(Strings.Error_CallNotInProgress, skypeID));
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, string.Format(Strings.Error_SendingAudioMessage, skypeID));
                Logger.Write(ex);
            }
        }
Example #16
0
        private void Remove(string portName)
        {
            SerialPort port = ports[portName];

            // We have no more handlers for this port, remove it from everything
            port.DataReceived -= this.DataReceived;

            if (port.IsOpen)
            {
                try
                {
                    port.Close();
                }
                catch
                {
                    Debug.WriteLine("Unable to close COM port: " + port.PortName);
                    ErrorLog.AddError(ErrorType.Failure, "Unable to close COM port. Ensure port is available or device plugged in.");
                }
            }

            portHandlers.Remove(port);
            portSettings.Remove(portName);
            ports.Remove(portName);

            if (ports.Count == 0)
            {
                // we have no more open ports, lets end the timer
                timer.Stop();
            }
        }
Example #17
0
        public void Load()
        {
            if (File.Exists(settingsFile))
            {
                using (FileStream stream = new FileStream(settingsFile, FileMode.Open))
                {
                    try
                    {
                        // Empty the connection list (should be empty already)
                        mayhem.ConnectionList.Clear();

                        // Load all the serialized connections
                        List <Type> allTypes = new List <Type>();
                        allTypes.AddRange(mayhem.EventList.GetAllTypesInModules());
                        allTypes.AddRange(mayhem.ReactionList.GetAllTypesInModules());
                        mayhem.LoadConnections(ConnectionList.Deserialize(stream, allTypes));

                        Logger.WriteLine("Starting up with " + mayhem.ConnectionList.Count + " connections");
                    }
                    catch (SerializationException e)
                    {
                        ErrorLog.AddError(ErrorType.Failure, "Error loading saved data");
                        Logger.WriteLine("(De-)SerializationException " + e);
                    }
                }
            }

            RunList.ItemsSource = mayhem.ConnectionList;

            Errors = ErrorLog.Errors;
        }
Example #18
0
        protected override void OnEnabling(EnablingEventArgs e)
        {
            base.OnEnabling(e);

            if (!e.Cancel)
            {
                ThreadPool.QueueUserWorkItem(o =>
                {
                    try
                    {
                        bool found = false;
                        string saveTokenActivities = string.Empty;

                        GPlusActivities activities = apiHelper.ListActivities();

                        do
                        {
                            saveTokenActivities = activities.nextPageToken;
                            foreach (GPlusActivity activity in activities.items)
                            {
                                if (activity.url.Equals(activityLink))
                                {
                                    activityId = activity.id;

                                    found = true;
                                    break;
                                }
                            }

                            if (found)
                            {
                                break;
                            }

                            activities = apiHelper.ListActivities(activities.nextPageToken);
                        } while (!string.IsNullOrEmpty(saveTokenActivities));

                        if (found)
                        {
                            StartTimer(100);
                        }
                        else
                        {
                            ErrorLog.AddError(ErrorType.Failure, string.Format(Strings.General_Incorrect, Strings.General_ActivityID));

                            e.Cancel = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorLog.AddError(ErrorType.Failure, Strings.GooglePlus_EventCouldntBeEnabled);
                        Logger.Write(ex);

                        e.Cancel = true;
                        return;
                    }
                });
            }
        }
Example #19
0
 protected override void OnEnabling(EnablingEventArgs e)
 {
     if (!Directory.Exists(fileName))
     {
         ErrorLog.AddError(ErrorType.Failure, Strings.General_DirectoryNotFound);
         e.Cancel = true;
     }
 }
Example #20
0
 protected override void OnEnabling(EnablingEventArgs e)
 {
     if (!Utilities.ConnectedToInternet())
     {
         ErrorLog.AddError(ErrorType.Warning, Strings.Internet_NotConnected);
     }
     timer.Start();
 }
Example #21
0
 private void InternetError()
 {
     if (showError)
     {
         ErrorLog.AddError(ErrorType.Warning, String.Format(Strings.Internet_NotConnected, "Facebook " + Title));
         showError = false;
     }
 }
Example #22
0
 protected override void OnEnabling(EnablingEventArgs e)
 {
     if (!File.Exists(FileName))
     {
         ErrorLog.AddError(ErrorType.Failure, Strings.RunProgram_FileNotFound);
         e.Cancel = true;
     }
 }
Example #23
0
        protected bool VerifyDeviceVisibility()
        {
            if (isFirstRun)
            {
                timer.Interval = seconds * 1000;
                isFirstRun     = false;
            }

            try
            {
                // Calling this method will return a list of the currently visible devices.
                // Note that this method takes up to 10 seconds to complete, in order to have accurate results.
                List <BluetoothDeviceInfo> newDevices = bluetoothClient.DiscoverDevices(10, false, false, false, true).ToList();

                bool found = false;

                // We get the current available devices and we see if the device we are looking for is in the list. If so we update the values of isVisible and wasVisible.
                foreach (BluetoothDeviceInfo device in newDevices)
                {
                    // It is possible that the name of the device is not received correctly, so when we manage to get it's address we will save it and also use it for comparison.
                    if ((deviceAddress != null && device.DeviceAddress.Equals(deviceAddress)) || device.DeviceName.Equals(deviceName))
                    {
                        if (isFirstRun)
                        {
                            isVisible  = true;
                            wasVisible = true;
                        }

                        // The device we search for is in the list of the available devices.
                        found         = true;
                        deviceAddress = device.DeviceAddress;

                        if (!isVisible)
                        {
                            wasVisible = false;
                            isVisible  = true;
                        }

                        break;
                    }
                }

                if (!found && isVisible)
                {
                    wasVisible = true;
                    isVisible  = false;
                }

                return(true);
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.BT_ErrorMonitoringBluetooth);
                Logger.Write(ex);

                return(false);
            }
        }
Example #24
0
        public void SavePicture(object pShapes)
        {
            int count = 0;
            List <OPowerPoint.Shape> shapes;

            shapes = pShapes as List <OPowerPoint.Shape>;

            if (shapes == null)
            {
                return;
            }

            FileStream stream = null;

            try
            {
                foreach (OPowerPoint.Shape shape in shapes)
                {
                    shape.Copy();

                    bool containsImage = Clipboard.ContainsImage();

                    if (containsImage)
                    {
                        count++;

                        BitmapSource image = Clipboard.GetImage();

                        stream = new FileStream(fileName + "\\" + presentationName + "_pic" + count + ".jpg", FileMode.Create);

                        JpegBitmapEncoder encoder = new JpegBitmapEncoder();

                        encoder.Frames.Add(BitmapFrame.Create(image));
                        encoder.Save(stream);

                        stream.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.PowerPoint_CantSavePictures);
                Logger.WriteLine(ex.Message);

                try
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }
                catch (IOException e)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.CantCloseFileStream);
                    Logger.WriteLine(e);
                }
            }
        }
Example #25
0
        /// <summary>
        /// If an instance of the Lync application exits this method will send the selected file to the predefined User Id.
        /// </summary>
        public override void Perform()
        {
            try
            {
                lyncClient = LyncClient.GetClient();
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.Lync_ApplicationNotFound);
                Logger.Write(ex);

                return;
            }

            try
            {
                self = lyncClient.Self;

                if (self == null)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.Lync_NotLoggedIn);
                    return;
                }

                try
                {
                    Contact contact = self.Contact.ContactManager.GetContactByUri(userId);
                }
                catch (Exception ex)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.Lync_NoUserId);
                    Logger.Write(ex);
                    return;
                }

                Automation automation = LyncClient.GetAutomation();

                var participants = new List <string>();
                var contextData  = new Dictionary <AutomationModalitySettings, object>();

                contextData.Add(AutomationModalitySettings.FilePathToTransfer, fileName);
                contextData.Add(AutomationModalitySettings.FileIsShared, true);

                participants.Add(userId);

                automation.BeginStartConversation(AutomationModalities.FileTransfer, participants, contextData, null, automation);
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.Lync_ReactionCouldntPerform);
                Logger.Write(ex);
            }
            finally
            {
                lyncClient = null;
            }
        }
Example #26
0
 protected override void OnEnabling(EnablingEventArgs e)
 {
     m = new MPlayer();
     if (!File.Exists(SoundPath))
     {
         ErrorLog.AddError(ErrorType.Warning, Strings.PlaySound_FileNotFound);
         e.Cancel = true;
     }
 }
Example #27
0
        public override void Perform()
        {
            if (isPerforming)
            {
                ErrorLog.AddError(ErrorType.Failure, "Waiting for last snapshot to save");
                return;
            }
            if (!selectedCameraConnected)
            {
                ErrorLog.AddError(ErrorType.Failure, "Waiting for webcam to become available");
                return;
            }
            if (selectedCameraIndex != -1 && selectedCameraConnected && webcambuffer != null)
            {
                isPerforming = true;
                Bitmap image = webcambuffer.GetLastBufferedItem();
                try
                {
                    if (image != null)
                    {
                        string savedPath = SaveImage(ref image);
                        //save image
                        if (playShutterSound)
                        {
                            SoundPlayer shutterSound = new SoundPlayer(Properties.Resources.shutterSound);
                            shutterSound.Play();
                        }

                        if (showPreview)
                        {
                            ImagePopup popup = new ImagePopup();
                            popup.ShowPopup(1000, savedPath);
                            popup = null;
                        }
                    }
                }
                catch
                {
                    Logger.WriteLine("Exception while saving picture");
                    ErrorLog.AddError(ErrorType.Failure, "Could not save picture");
                }
                finally
                {
                    if (image != null)
                    {
                        image.Dispose();
                    }
                    image = null;
                }
                isPerforming = false;
            }
            else
            {
                ReleasePreviousBuffers();
                ErrorLog.AddError(ErrorType.Failure, "Webcam snapshot is disabled because selected camera was not found");
            }
        }
        /// <summary>
        /// This method is called when the timer.Elapsed event is raised and checks if the network with the strongest signal has changed since the last check.
        /// </summary>
        protected override void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            timer.Stop();

            try
            {
                bool found = false;
                foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
                {
                    newMaximumQualityValue = 0;

                    foreach (Wlan.WlanAvailableNetwork network in wlanIface.GetAvailableNetworkList(0))
                    {
                        if (GetStringForSSID(network.dot11Ssid).Equals(GetStringForSSID(strongestNetwork.dot11Ssid)))
                        {
                            found = true;

                            signalQualityStrongestNetwork = network.wlanSignalQuality;
                        }
                        else
                        {
                            if (!GetStringForSSID(network.dot11Ssid).Equals(GetStringForSSID(strongestNetwork.dot11Ssid)) && newMaximumQualityValue < network.wlanSignalQuality)
                            {
                                newMaximumQualityValue = network.wlanSignalQuality;
                                newerStrongestNetwork  = network;
                            }
                        }
                    }

                    if (found == false)
                    {
                        signalQualityStrongestNetwork = 0; // The network is no longer available.
                    }
                }

                if (newMaximumQualityValue > signalQualityStrongestNetwork)
                {
                    signalQualityStrongestNetwork = newMaximumQualityValue;
                    strongestNetwork = newerStrongestNetwork;

                    Trigger();
                }
            }
            catch (Win32Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.WiFi_CantGetNetworks);
                Logger.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.WiFi_CantGetNetworks);
                Logger.Write(ex);
            }

            timer.Start();
        }
Example #29
0
        protected int LookforSelectedCamera(bool force = false)
        {
            bool selectedCameraFound = false;

            selectedCameraConnected = false;
            if (!IsEnabled && !force)
            {
                return(-1);
            }
            int numberConnectedCameras = WebcamManager.NumberConnectedCameras();

            if (numberConnectedCameras == 0)
            {
                selectedCameraConnected = false;
                Logger.WriteLine("No camera available");
                ErrorLog.AddError(ErrorType.Failure, "Motion detection is disabled because no camera was detected");
                return(-1);
            }
            int index = -1;

            if (selectedCameraPath == default(string))
            {
                ErrorLog.AddError(ErrorType.Message, "No webcam configuration. Defaulting to first available webcam.");
                return(-1);
            }
            else
            {
                for (int i = 0; i < numberConnectedCameras; i++)
                {
                    if (WebcamManager.GetCamera(i).WebCamPath == selectedCameraPath)
                    {
                        if (WebcamManager.GetCamera(i).IsActive)
                        {
                            index = i;
                            selectedCameraConnected = true;
                            selectedCameraFound     = true;
                            break;
                        }
                        else if (WebcamManager.StartCamera(i, captureWidth, captureHeight))
                        {
                            index = i;
                            selectedCameraConnected = true;
                            selectedCameraFound     = true;
                            break;
                        }
                    }
                }

                if (!selectedCameraFound && numberConnectedCameras > 0)
                {
                    ErrorLog.AddError(ErrorType.Failure, "The originally selected camera is not available.");
                }
                return(index);
            }
        }
Example #30
0
        /// <summary>
        /// Grabs the current weather information for the city / zipcode being watched
        /// </summary>
        private void CheckWeather(object sender, EventArgs e)
        {
            // Test for internet connection
            if (Utilities.ConnectedToInternet())
            {
                internetFlag = true;
                try
                {
                    // get the xml data
                    WebRequest webRequest = WebRequest.Create("http://www.google.com/ig/api?weather=" + zipCode.Replace(" ", "%20"));
                    using (WebResponse webResponse = webRequest.GetResponse())
                    {
                        HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                        webRequest.CachePolicy = noCachePolicy;
                        using (Stream responseStream = webResponse.GetResponseStream())
                        {
                            // Used to crash on "Paris" because of encoding issues, now using
                            // Western-European Windows encoding
                            StreamReader s = new StreamReader(responseStream, Encoding.GetEncoding(1252));
                            XmlReader    r = XmlReader.Create(s);

                            r.ReadToFollowing("temp_f");
                            int temp = Convert.ToInt32(r.GetAttribute("data"));

                            bool isBelowOrAbove = (checkBelow && temp >= temperature) || (!checkBelow && temp <= temperature);

                            // if below desired temperature and watching for below, trigger
                            // if above desired temperature and watching for abovem trigger
                            if (isBelowOrAbove)
                            {
                                bool reset = ((temp == temperature + Offset) && checkBelow) || ((temp == temperature - Offset) && !checkBelow);
                                if (!hasPassed)
                                {
                                    hasPassed = true;
                                    Trigger();
                                }
                                else if (reset)
                                {
                                    hasPassed = false;
                                }
                            }
                        }
                    }
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.ToString());
                }
            }
            else if (internetFlag)
            {
                internetFlag = false;
                ErrorLog.AddError(ErrorType.Warning, String.Format(Strings.Internet_NotConnected, "Weather"));
            }
        }
Example #31
0
 public static IodineModule CompileModule(ErrorLog errorLog, string file)
 {
     if (FindModule (file) != null) {
         Tokenizer lexer = new Tokenizer (errorLog, File.ReadAllText (FindModule (file)), file);
         TokenStream tokenStream = lexer.Scan ();
         if (errorLog.ErrorCount > 0)
             return null;
         Parser parser = new Parser (tokenStream);
         AstRoot root = parser.Parse ();
         if (errorLog.ErrorCount > 0)
             return null;
         SemanticAnalyser analyser = new SemanticAnalyser (errorLog);
         SymbolTable symbolTable = analyser.Analyse (root);
         if (errorLog.ErrorCount > 0)
             return null;
         IodineCompiler compiler = new IodineCompiler (errorLog, symbolTable, Path.GetFullPath (file));
         IodineModule module = new IodineModule (Path.GetFileNameWithoutExtension (file));
         compiler.CompileAst (module, root);
         if (errorLog.ErrorCount > 0)
             return null;
         return module;
     } else {
         errorLog.AddError (ErrorType.ParserError, new Location (0, 0, file),
             "Could not find module {0}", file);
         return null;
     }
 }