Esempio n. 1
0
        private void MoveUpdateToTemporaryFile(AutoUpdateInfo aInfo)
        {
            string tempFile = CreateTemporaryFilename();

            try
            {
                if (aInfo.FileName != null)
                {
                    File.Move(aInfo.FileName, tempFile);
                }
            }
            catch (IOException e)
            {
                UserLog.WriteLine(String.Format("Cannot move {0} to {1}", Path.GetFileName(aInfo.Uri.LocalPath), tempFile));
                UserLog.WriteLine(e.ToString());
            }
        }
Esempio n. 2
0
 private void Load()
 {
     lock (iLock)
     {
         Trace.WriteLine(Trace.kCore, "Loading settings from " + iFilename);
         if (File.Exists(iFilename))
         {
             LoadOptionsFile(iFilename);
         }
         else
         {
             UserLog.WriteLine("Could not find options file " + iFilename);
             Trace.WriteLine(Trace.kCore, "Could not find options file " + iFilename);
             MigrateOldOptions();
         }
     }
 }
Esempio n. 3
0
        private void ProcessRequests()
        {
            while (true)
            {
                iEvent.WaitOne();

                Monitor.Enter(iLockObject);

                if (iPendingRequests.Count > 0 && IsRunning)
                {
                    ImageRequest             request = iPendingRequests[0];
                    IImageLoader <ImageType> loader  = iImageLoader;
                    iPendingRequests.Remove(request);
                    iExecutingRequests.Add(request);
                    Monitor.Exit(iLockObject);
                    try
                    {
                        IImage <ImageType> img = loader.LoadImage(new Uri(request.Uri), iDownscaleImageSize);
                        img.IncrementReferenceCount();
                        lock (iLockObject)
                        {
                            Add(request.Uri, img);
                            iExecutingRequests.Remove(request);
                        }
                        OnEventImageAdded(request, img);
                        img.DecrementReferenceCount();
                    }
                    catch (Exception ex)
                    {
                        UserLog.WriteLine("Error downloading image: " + request.Uri + ", " + ex.ToString());
                        lock (iLockObject)
                        {
                            iImageCacheFailures.Add(request.Uri);
                            iExecutingRequests.Remove(request);
                        }
                        OnEventRequestFailed(request.Uri);
                    }
                }
                else
                {
                    iEvent.Reset();
                    Monitor.Exit(iLockObject);
                }
            }
        }
Esempio n. 4
0
        public AutoUpdateInfo CheckForUpdate()
        {
            try
            {
                WebRequest request = WebRequest.Create(iUpdateFeedLocation);
                request.Credentials = CredentialCache.DefaultCredentials;
                if (request.Proxy != null)
                {
                    request.Proxy.Credentials = CredentialCache.DefaultCredentials;
                }

                WebResponse response = request.GetResponse();

                using (Stream stream = response.GetResponseStream())
                {
                    ReleaseFeed feed = new ReleaseFeed(stream);

                    IReleaseJson update = feed.CheckForUpdate(iHelper.Version, iApplicationQuality, iApplicationTarget, Environment.OSVersion.Version.ToString(), DesiredQuality);

                    if (update != null)
                    {
                        UserLog.WriteLine(String.Format("{0} update available: {1}", update.Quality, update.Version));

                        return(new AutoUpdateInfo(iApplicationName,
                                                  update.Version,
                                                  feed.Json.History(),
                                                  update.UpdateUri(),
                                                  update.Quality(),
                                                  VersionSupport.Family(iHelper.Version) != VersionSupport.Family(update.Version)));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLine(String.Format("Error caught checking for updates: {0}", ex.ToString()));
            }

            return(null);
        }
Esempio n. 5
0
        public bool ApplyUpdate(AutoUpdateInfo aInfo)
        {
            bool result = true;

            try
            {
                Assembly updateAssembly = Assembly.LoadFile(new FileInfo(aInfo.FileName).FullName);
                ExtractFiles(aInfo, updateAssembly);
            }
            catch (Exception e)
            {
                InvalidUpdateFile(aInfo);
                UserLog.WriteLine(String.Format("Error applying update: {0}", e));
                result = false;
            }

            CleanupTemporaryFiles();        // do some housekeeping

            return(result);
        }
Esempio n. 6
0
        private void StopStack()
        {
            if (iStatus.State != EStackState.eStopped)
            {
                Trace.WriteLine(Trace.kCore, "Stack.StopStack() stopping stack...");
                UserLog.WriteLine(DateTime.Now + ": Linn.Stack stopping...");

                if (iStackStarted && iStack != null)
                {
                    iStack.Stop();
                }

                iStatus       = new StackStatus(EStackState.eStopped, null);
                iStackStarted = false;
                iInterface    = null;

                Trace.WriteLine(Trace.kCore, "Stack.StopStack() stack stopped");
                UserLog.WriteLine(DateTime.Now + ": Linn.Stack stop ok");
            }
        }
Esempio n. 7
0
        private void LoadOptionsFile(string aFilename)
        {
            try
            {
                XmlDocument document = new XmlDocument();
                document.Load(aFilename);

                XmlNodeList entryNodeList = document.SelectNodes("Dictionary/Entry");
                foreach (XmlNode entryNode in entryNodeList)
                {
                    // get the xml nodes
                    XmlNode keyNode   = entryNode.SelectSingleNode("Key");
                    XmlNode valueNode = entryNode.SelectSingleNode("Value");

                    // add the dictionary entry
                    if (keyNode != null && valueNode != null)
                    {
                        iLoadDictionary.Add(keyNode.InnerText, valueNode.InnerText);

                        try
                        {
                            if (iLoadDictionary["room"] == "First Discovered")
                            {
                                iLoadDictionary["room"] = "Last Selected";
                            }
                        }
                        catch (Exception)
                        {
                            Trace.WriteLine(Trace.kCore, "Failed to migrate startup room setting");
                        }

                        Trace.WriteLine(Trace.kCore, "Loaded: " + keyNode.InnerText + " [" + valueNode.InnerText + "]");
                    }
                }
            }
            catch (Exception e)
            {
                UserLog.WriteLine("Options file corrupt: " + e.ToString());
                Trace.WriteLine(Trace.kCore, "Options file corrupt: " + e.ToString());
            }
        }
Esempio n. 8
0
        public static void RefreshWifiInfo(Context aContext)
        {
            WifiManager      wifi     = (WifiManager)aContext.GetSystemService(Context.WifiService);
            NetworkInfoModel newModel = null;

            if (wifi != null && wifi.IsWifiEnabled)
            {
                Android.Net.Wifi.WifiInfo networkInfo = wifi.ConnectionInfo;// as Android.Net.Wifi.WifiInfo;
                newModel = new NetworkInfoModel(
                    networkInfo.SSID,
                    networkInfo.MacAddress,
                    ENetworkInterfaceType.eEthernet,
                    new System.Net.IPAddress(networkInfo.IpAddress),
                    null,
                    ENetworkInterfaceComponent.eIPv4,
                    string.Empty,
                    wifi.WifiState == Android.Net.WifiState.Enabled ? EOperationalStatus.eUp : EOperationalStatus.eDown,
                    //networkInfo.SupplicantState == Android.Net.Wifi.SupplicantState.Completed ? EOperationalStatus.eUp : EOperationalStatus.eDown,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    new List <System.Net.IPAddress>()
                    );
                networkInfo.Dispose();
                wifi.Dispose();
                UserLog.WriteLine("RefreshWifiInfo(): " + newModel.Name + ", " + newModel.IPAddress + ", " + newModel.OperationalStatus);
            }
            else
            {
                UserLog.WriteLine("RefreshWifiInfo(): No Network");
            }
            sWifiInterface = newModel;
        }
Esempio n. 9
0
        public void Dispose()
        {
            // remove trace listeners
            if (iTraceFile != null)
            {
                Trace.RemoveListener(iTraceFile);
                iTraceFile.Dispose();
                iTraceFile = null;
            }

            // remove user log listener
            if (iUserLogFile != null)
            {
                UserLog.RemoveListener(iUserLogFile);
                iUserLogFile.Dispose();
                iUserLogFile = null;
            }

            // dispose of network interface option
            if (iOptionNetworkInterface != null)
            {
                iOptionNetworkInterface.Dispose();
            }
        }
Esempio n. 10
0
        public static List <NetworkInfoModel> GetAllNetworkInterfaces()
        {
            List <NetworkInfoModel> adaptors = new List <NetworkInfoModel>();

            System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

            foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics)
            {
                string adapterName        = adapter.Name;
                string adapterDescription = adapter.Description;
                string macAddress         = adapter.GetPhysicalAddress().ToString();

                ENetworkInterfaceComponent networkInterfaceComponent = (adapter.Supports(NetworkInterfaceComponent.IPv4))
                    ? ENetworkInterfaceComponent.eIPv4
                    : ENetworkInterfaceComponent.eUnknown;

                ENetworkInterfaceType networkInterfaceType = (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback)
                    ? ENetworkInterfaceType.eLoopBack
                    : ENetworkInterfaceType.eUnknown;

                // ignore loopback adapters, non IPv4 adapters
                if (networkInterfaceType == ENetworkInterfaceType.eLoopBack)
                {
                    UserLog.WriteLine(adapter.Description + " is loopback - ignored");
                    continue;
                }

                if (networkInterfaceComponent != ENetworkInterfaceComponent.eIPv4)
                {
                    UserLog.WriteLine(adapter.Description + " does not support IPv4 - ignored");
                    continue;
                }

                bool?supportsMulticast = null;
                bool?isRecieveOnly     = null;
                try
                {
                    supportsMulticast = adapter.SupportsMulticast;
                    isRecieveOnly     = adapter.IsReceiveOnly;
                }
                catch (PlatformNotSupportedException)
                {
                    // Multicast, IsReceiveOnly support only defined in Windows XP and greater
                }

                EOperationalStatus    operationalStatus = (EOperationalStatus)((int)adapter.OperationalStatus);
                IPInterfaceProperties properties        = adapter.GetIPProperties();

                bool?isDHCPEnabled = null;
                bool?isAutoPrivateAddressEnabled = null;
                int? mtu = null;

                try
                {
                    IPv4InterfaceProperties ipv4 = properties.GetIPv4Properties();
                    if (ipv4 != null)
                    {
                        isDHCPEnabled = ipv4.IsDhcpEnabled;
                        isAutoPrivateAddressEnabled = ipv4.IsAutomaticPrivateAddressingEnabled;
                        mtu = ipv4.Mtu;
                    }
                }
                catch { } // throws an error in mono 2.6

                List <IPAddress> gatewayAddress = new List <IPAddress>();
                foreach (GatewayIPAddressInformation gateway in properties.GatewayAddresses)
                {
                    gatewayAddress.Add(gateway.Address);
                }

                int i = 0;
                UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses;
                foreach (UnicastIPAddressInformation ip in uniCast)
                {
                    // only take ipv4 address of adapter (may have ipv4 and ipv6)
                    if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        NetworkInfoModel adaptor = new NetworkInfoModel(adapterDescription
                                                                        , adapterName + ((i == 0) ? "" : " (" + i.ToString() + ")")
                                                                        , networkInterfaceType
                                                                        , ip.Address
                                                                        , supportsMulticast
                                                                        , networkInterfaceComponent
                                                                        , macAddress
                                                                        , operationalStatus
                                                                        , isRecieveOnly
                                                                        , isDHCPEnabled
                                                                        , isAutoPrivateAddressEnabled
                                                                        , mtu
                                                                        , properties.IsDnsEnabled
                                                                        , properties.IsDynamicDnsEnabled
                                                                        , properties.DnsSuffix
                                                                        , gatewayAddress);

                        adaptors.Add(adaptor);
                        ++i;
                        UserLog.WriteLine(adapterName + " (" + ip.Address.ToString() + ") is supported");
                        Trace.WriteLine(Trace.kCore, adapterName + " [" + adapterDescription + "] (" + ip.Address.ToString() + ") is supported");
                    }
                }
            }

            return(adaptors);
        }
 private void InterfaceChanged(IntPtr aStoreRef, IntPtr changedKeys, IntPtr info)
 {
     UserLog.WriteLine("InterfaceChanged");
     Trace.WriteLine(Trace.kCore, "InterfaceChanged");
     OnEventNetworkChanged();
 }
Esempio n. 12
0
        public AutoUpdateInfo CheckForUpdate()
        {
            WebResponse response = null;
            Stream      stream   = null;

            try
            {
                WebRequest request = WebRequest.Create(iUpdateFeedLocation);
                request.Credentials = CredentialCache.DefaultCredentials;
                if (request.Proxy != null)
                {
                    request.Proxy.Credentials = CredentialCache.DefaultCredentials;
                }
                response = request.GetResponse();
                stream   = response.GetResponseStream();

                XmlDocument       document = new XmlDocument();
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.XmlResolver = null;
                settings.ProhibitDtd = true;
                XmlReader xmlReader = XmlTextReader.Create(stream, settings);
                document.Load(xmlReader);

                XmlNamespaceManager xmlNsMan = new XmlNamespaceManager(document.NameTable);
                xmlNsMan.AddNamespace("ns", "urn:linn-co-uk/autoupdate");

                string latestVersion = iHelper.Version;
                string product       = iHelper.Product;

                AutoUpdateInfo result = null;

                KeyValuePair <EUpdateType, string>[] versionTypeNodeNames = new KeyValuePair <EUpdateType, string>[]
                {
                    new KeyValuePair <EUpdateType, string>(EUpdateType.Stable, "stable"),
                    new KeyValuePair <EUpdateType, string>(EUpdateType.Beta, "beta"),
                    new KeyValuePair <EUpdateType, string>(EUpdateType.Development, "development"),
                    new KeyValuePair <EUpdateType, string>(EUpdateType.Nightly, "nightly")
                };

                foreach (XmlNode applicationNode in document.SelectNodes(string.Format("/ns:autoupdate/ns:updateinfo[@version='{0}']/ns:application[@name='{1}']", iUpdateVersion, iApplicationName), xmlNsMan))
                {
                    Uri historyUri = new Uri(applicationNode.SelectSingleNode("ns:history", xmlNsMan).FirstChild.Value);

                    foreach (KeyValuePair <EUpdateType, string> versionType in versionTypeNodeNames)
                    {
                        if ((UpdateTypes & versionType.Key) == versionType.Key)
                        {
                            foreach (XmlNode versionNode in applicationNode.SelectNodes(string.Format("ns:{0}", versionType.Value), xmlNsMan))
                            {
                                string version = versionNode.Attributes["version"].Value;

                                if (VersionSupport.CompareVersions(version, latestVersion) > 0 ||
                                    (VersionSupport.CompareVersions(version, latestVersion) == 0 && versionType.Key > iApplicationBuildType))
                                {
                                    XmlNode uriNode = versionNode.SelectSingleNode(String.Format("ns:url[@target='{0}']", iApplicationTarget), xmlNsMan);
                                    if (uriNode != null)
                                    {
                                        UserLog.WriteLine(String.Format("{0} update available: {1}", versionType.Value, version));
                                        Uri uri = new Uri(uriNode.InnerText);
                                        result        = new AutoUpdateInfo(iApplicationName, version, historyUri, uri, versionType.Key, VersionSupport.Family(iHelper.Version) != VersionSupport.Family(version));
                                        latestVersion = version;
                                    }
                                }
                            }
                        }
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                UserLog.WriteLine(String.Format("Error caught checking for updates: {0}", ex.ToString()));
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
            }

            return(null);
        }
Esempio n. 13
0
        public void NetworkChanged()
        {
            NetworkInterface newInterface = null;

            lock (this)
            {
                // rebuild list of available interfaces
                iAllowedInterfaces = new List <NetworkInterface>();
                iAllowedInterfaces.Add(new NetworkInterface());

                foreach (NetworkInfoModel i in NetworkInfo.GetAllNetworkInterfaces())
                {
                    if (i.OperationalStatus == EOperationalStatus.eUp ||
                        i.OperationalStatus == EOperationalStatus.eUnknown)
                    {
                        // don't add 3G network card on iPads/iPhones
                        if (i.Name != "pdp_ip0")
                        {
                            iAllowedInterfaces.Add(new NetworkInterface(i));
                        }
                    }
                }

                // send to user log
                string userLogMsg = DateTime.Now + ": Network interface event received. Available interfaces:";
                for (int i = 1; i < iAllowedInterfaces.Count; i++)
                {
                    userLogMsg += Environment.NewLine + DateTime.Now + ":     " + iAllowedInterfaces[i].ToString();
                }
                UserLog.WriteLine(userLogMsg);

                // set the default interface - if there is only 1 real interface - set this as default
                if (iAllowedInterfaces.Count == 2)
                {
                    iDefault = iAllowedInterfaces[1];
                }
                else
                {
                    iDefault = iAllowedInterfaces[0];
                }

                // update the existing interface
                switch (iInterface.Status)
                {
                case NetworkInterface.EStatus.eUnconfigured:
                    if (iDefault.Status != NetworkInterface.EStatus.eUnconfigured)
                    {
                        // interface unconfigured -> available/unavailable default
                        newInterface = iDefault;
                    }
                    break;

                case NetworkInterface.EStatus.eUnavailable:
                {
                    NetworkInterface found = FindInterface(iInterface.Name);
                    if (found != null && found.Status == NetworkInterface.EStatus.eAvailable)
                    {
                        // interface unavailable -> available
                        newInterface = found;
                    }
                }
                break;

                case NetworkInterface.EStatus.eAvailable:
                {
                    NetworkInterface found = FindInterface(iInterface.Name);
                    if (found != null)
                    {
                        if (found.Status == NetworkInterface.EStatus.eAvailable)
                        {
                            if (!iInterface.Info.IPAddress.Equals(found.Info.IPAddress))
                            {
                                // interface available -> available (ip address change)
                                newInterface = found;
                            }
                        }
                        else
                        {
                            // interface available -> unavailable
                            newInterface = found;
                        }
                    }
                    else
                    {
                        // interface available -> unavailable
                        newInterface = new NetworkInterface(iInterface.Name);
                    }
                }
                break;
                }

                if (newInterface != null)
                {
                    iInterface = newInterface;
                }

                Trace.WriteLine(Trace.kCore, "OptionNetworkInterface.NetworkChange(): Network interface event - " + iInterface + " -> " + newInterface);
                UserLog.WriteLine(DateTime.Now + ": Network interface event - " + iInterface + " -> " + newInterface);
            }

            EventHandler <EventArgs> eventAllowedChanged = EventAllowedChanged;

            if (eventAllowedChanged != null)
            {
                eventAllowedChanged(this, EventArgs.Empty);
            }

            EventHandler <EventArgs> eventValueChanged = EventValueChanged;

            if (newInterface != null && eventValueChanged != null)
            {
                eventValueChanged(this, EventArgs.Empty);
            }
        }
Esempio n. 14
0
        private void StartStack(NetworkInterface aInterface)
        {
            iInterface    = aInterface;
            iStackStarted = false;

            switch (aInterface.Status)
            {
            case NetworkInterface.EStatus.eUnconfigured:
                iStatus = new StackStatus(EStackState.eNoInterface, iInterface);

                Trace.WriteLine(Trace.kCore, "Stack.StartStack() no configured interface");
                UserLog.WriteLine(DateTime.Now + ": Linn.Stack start failed - no interface is configured");
                break;

            case NetworkInterface.EStatus.eUnavailable:
                iStatus = new StackStatus(EStackState.eNonexistentInterface, iInterface);

                Trace.WriteLine(Trace.kCore, "Stack.StartStack() configured interface error");
                UserLog.WriteLine(DateTime.Now + ": Linn.Stack start failed - configured interface is unavailable " + iInterface.ToString());
                break;

            case NetworkInterface.EStatus.eAvailable:
                try
                {
                    Trace.WriteLine(Trace.kCore, "Stack.StartStack() starting...");
                    UserLog.WriteLine(DateTime.Now + ": Linn.Stack starting... " + iInterface.ToString());

                    if (iStack != null)
                    {
                        iStack.Start(iInterface.Info.IPAddress);
                    }
                    iStatus       = new StackStatus(EStackState.eOk, iInterface);
                    iStackStarted = true;

                    Trace.WriteLine(Trace.kCore, "Stack.StartStack() OK");
                    UserLog.WriteLine(DateTime.Now + ": Linn.Stack start ok " + iInterface.ToString());
                }
                catch (Exception e)
                {
                    iStatus       = new StackStatus(EStackState.eBadInterface, iInterface);
                    iStackStarted = false;

                    Trace.WriteLine(Trace.kCore, "Stack.StartStack() failure: " + e.ToString());
                    Console.Write("Stack.StartStack() failure: " + e.ToString());
                    UserLog.WriteLine(DateTime.Now + ": Linn.Stack start failed " + iInterface.ToString());
                    UserLog.WriteLine("Error Message: " + e.Message);
                    UserLog.WriteLine("Error Message: " + e.ToString());

                    // stop the stack to cleanup any stack components that were started
                    if (iStack != null)
                    {
                        iStack.Stop();
                    }
                }
                break;

            default:
                Assert.Check(false);
                break;
            }
        }
Esempio n. 15
0
        private void InterfaceChanged(object sender, EventArgs e)
        {
            StackStatus newStatus;

            lock (this)
            {
                if (iStatus.State == EStackState.eStopped)
                {
                    return;
                }

                // get the current interface from the option
                NetworkInterface newInterface = iOption.Interface;

                if (newInterface.Name == iInterface.Name &&
                    iInterface.Status == NetworkInterface.EStatus.eAvailable &&
                    newInterface.Status == NetworkInterface.EStatus.eUnavailable)
                {
                    // the currently available configured interface has become unavailable e.g. gone into standby
                    // - do not stop the stack just yet as this will leave lingering subscriptions
                    iInterface = newInterface;
                    iStatus    = new StackStatus(EStackState.eNonexistentInterface, iInterface);

                    Trace.WriteLine(Trace.kCore, "Stack.InterfaceChanged() interface unavailable");
                    UserLog.WriteLine(DateTime.Now + ": Linn.Stack interface now unavailable " + iInterface.ToString());
                }
                else if (newInterface.Name == iInterface.Name &&
                         iInterface.Status == NetworkInterface.EStatus.eUnavailable &&
                         newInterface.Status == NetworkInterface.EStatus.eAvailable)
                {
                    // the currently unavailable configured interface has become available e.g. come out of standby
                    // - restart the stack
                    Trace.WriteLine(Trace.kCore, "Stack.InterfaceChanged() interface now available");
                    UserLog.WriteLine(DateTime.Now + ": Linn.Stack interface now available " + newInterface.ToString());

                    // now that the interface is available again, the stack can be stopped to cleanup existing
                    // subscriptions
                    StopStack();

                    // a pause for coming out of standby - on the PDA, even though it has a valid IP
                    // address, the interface is still not fully operational
                    System.Threading.Thread.Sleep(5000);

                    StartStack(newInterface);
                }
                else
                {
                    // all other interface changes, including switching to a different physical interface
                    // just restart the stack
                    StopStack();
                    StartStack(newInterface);
                }

                newStatus = iStatus;
            }

            EventHandler <EventArgsStackStatus> ev = EventStatusChanged;

            if (ev != null)
            {
                ev(this, new EventArgsStackStatus(newStatus));
            }
        }
        private void CreateInterfaceChangedObserver()
        {
            try
            {
                unsafe
                {
                    iObserver = InterfaceChanged;
                    iCallout  = Marshal.GetFunctionPointerForDelegate(iObserver);
                    iContext  = new SCDynamicStoreContext();
                    iStore    = SCDynamicStoreCreate(IntPtr.Zero, kAddIPAddressListChangeCallbackSCF, iCallout, iContext);
                    if (iStore == IntPtr.Zero)
                    {
                        throw new ApplicationException("Failed to invoke SCDynamicStoreCreate");
                    }

                    iPattern = SCDynamicStoreKeyCreateNetworkServiceEntity(IntPtr.Zero, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4);
                    if (iPattern == IntPtr.Zero)
                    {
                        throw new ApplicationException("Failed to invoke SCDynamicStoreKeyCreateNetworkServiceEntity");
                    }

                    iPatternList = CFArrayCreate(IntPtr.Zero, new IntPtr[1] {
                        iPattern
                    }, 1, IntPtr.Zero);
                    if (iPatternList == IntPtr.Zero)
                    {
                        throw new ApplicationException("Failed to invoke CFArrayCreate");
                    }
                    bool setNotificationKeys = SCDynamicStoreSetNotificationKeys(iStore, IntPtr.Zero, iPatternList);
                    if (!setNotificationKeys)
                    {
                        throw new ApplicationException("Failed to invoke SCDynamicStoreSetNotificationKeys");
                    }
                    iRunLoopSource = SCDynamicStoreCreateRunLoopSource(IntPtr.Zero, iStore, 0);
                    if (iRunLoopSource == IntPtr.Zero)
                    {
                        throw new ApplicationException("Failed to invoke SCDynamicStoreCreateRunLoopSource");
                    }
                    iRunLoop = CFRunLoopGetMain();
                    if (iRunLoop == IntPtr.Zero)
                    {
                        throw new ApplicationException("Failed to invoke CFRunLoopGetMain");
                    }

                    IntPtr  bundle    = CFBundleGetBundleWithIdentifier(kBundleIdentifier);
                    IntPtr *stringRef = (IntPtr *)CFBundleGetDataPointerForName(bundle, kCFRunLoopCommonModes);
                    iModeString = *stringRef;

                    CFRunLoopAddSource(iRunLoop, iRunLoopSource, iModeString);
                    CFRelease(iPattern);
                    CFRelease(iPatternList);
                }
            }
            catch (Exception ex)
            {
                string message = "Error creating NetworkChangeWatcher: " + ex;
                UserLog.WriteLine(message);
                Trace.WriteLine(Trace.kCore, message);

                if (iPattern != IntPtr.Zero)
                {
                    CFRelease(iPattern);
                }

                if (iPatternList != IntPtr.Zero)
                {
                    CFRelease(iPatternList);
                }
                if (iStore != IntPtr.Zero)
                {
                    CFRelease(iStore);
                }
                if (iRunLoopSource != IntPtr.Zero)
                {
                    CFRelease(iRunLoopSource);
                }
            }
        }
Esempio n. 17
0
        public Helper(string[] aArgs)
        {
            iAssemblyAttributes = Linn.AssemblyInfo.GetAssemblyInfo();
            iLock        = new object();
            iErrorThrown = false;

            // create the data and exe paths
            iDataPath = SystemInfo.DataPathForApp(Title);

            if (!iDataPath.Exists)
            {
                try
                {
                    iDataPath.Create();
                }
                catch (IOException e)
                {
                    Console.WriteLine(e.Message + "\n");
                }
            }

            iExePath = SystemInfo.ExePathForApp(Title);



            // add the unhandled exception handler - this should catch all unhandled
            // exceptions in all threads
#if !DEBUG && !TRACE
            AppDomain.CurrentDomain.UnhandledException += UnhandledException;
#endif

            // initialise crash log dumpers
            iCrashLogDumpers = new List <ICrashLogDumper>();
            iCrashLogDumpers.Add(new CrashLogDumperStdout());
            // only add 1 crash file for several instances of the app
            string[] filenames = System.IO.Directory.GetFiles(".", "*.crash");
            if (filenames.Length == 0)
            {
                string exeNoExt  = Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName);
                string crashFile = Path.Combine(iDataPath.FullName, exeNoExt) + ".crash";
                iCrashLogDumpers.Add(new CrashLogDumperFile(crashFile));
            }


            // add trace listeners
            Trace.AddListener(new TraceListenerConsole());

            // remove unused log files
            filenames = System.IO.Directory.GetFiles(iDataPath.FullName, "*.log");
            foreach (string file in filenames)
            {
                try
                {
                    // delete the file and ignore exceptions - file may be in use
                    File.Delete(file);
                }
                catch (IOException) { }
            }
            iTraceFile = new TraceListenerFile(iDataPath.FullName);
            Trace.AddListener(iTraceFile);


            // add user log listener
            try
            {
                iUserLogFile = new UserLogFile(iDataPath.FullName);
                UserLog.AddListener(iUserLogFile);
            }
            catch (IOException) { }

            UserLog.WriteLine(Product + " v" + Version + " (" + Family + ")");

            // log the mono version if being used
            Type t = Type.GetType("Mono.Runtime");
            if (t != null)
            {
                MethodInfo displayName = t.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
                if (displayName != null)
                {
                    UserLog.WriteLine("Mono Version: " + displayName.Invoke(null, null));
                }
            }

            // create option parser
            iOptionParser       = new OptionParser(aArgs);
            iOptionParser.Usage = "usage: " + Title;
            // add the trace level option
            iOptionTraceLevel = new OptionParser.OptionString("-t", "--tracelevel", "kNone",
                                                              "Set the trace level for the application. Multiple levels specified in quotes.", "LEVEL1 [LEVEL2 LEVEL3 ...]");
            iOptionParser.AddOption(iOptionTraceLevel);

            iOptionNic = new OptionParser.OptionString("-i", "--interface", "0.0.0.0",
                                                       "Sets the interface to bind to", "INTERFACE");
            iOptionParser.AddOption(iOptionNic);

            ServicePointManager.DefaultConnectionLimit = 50;
            ServicePointManager.UseNagleAlgorithm      = false;
            ServicePointManager.Expect100Continue      = false;

            iOptionPages   = new List <IOptionPage>();
            iOptionManager = new OptionManager(Path.Combine(iDataPath.FullName, "Options.xml"));

            iOptionPage             = new OptionPage("Network");
            iOptionNetworkInterface = new OptionNetworkInterface("interface");
            iOptionPage.Add(iOptionNetworkInterface);

            // create the network stack
            iStack = new Stack(iOptionNetworkInterface);
        }
Esempio n. 18
0
        public void DownloadUpdate(AutoUpdateInfo aInfo)
        {
            iUpdateProgress = 0;
            if (EventUpdateProgress != null)
            {
                EventUpdateProgress(this, EventArgs.Empty);
            }

            int    startingPoint = 0;
            string tempFile      = string.Format("{0}{2}{1}", aInfo.Name, aInfo.Version, ".part");

            tempFile = Path.Combine(iUpdateFolder, tempFile);
            if (File.Exists(tempFile))
            {
                startingPoint = (int)(new FileInfo(tempFile).Length);
            }

            try
            {
                HttpWebRequest headRequest = (HttpWebRequest)WebRequest.Create(aInfo.Uri);
                headRequest.Method = "HEAD";
                HttpWebResponse headResponse  = (HttpWebResponse)headRequest.GetResponse();
                int             contentLength = Int32.Parse(headResponse.Headers[HttpResponseHeader.ContentLength]);

                if (contentLength > startingPoint)
                {
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(aInfo.Uri);
                    request.Credentials = CredentialCache.DefaultCredentials;
                    if (request.Proxy != null)
                    {
                        request.Proxy.Credentials = CredentialCache.DefaultCredentials;
                    }
                    request.AddRange(startingPoint);
                    HttpWebResponse response      = (HttpWebResponse)request.GetResponse();
                    Stream          responseSteam = response.GetResponseStream();
                    FileStream      fileStream    = null;
                    if (startingPoint == 0 || response.StatusCode != HttpStatusCode.PartialContent)
                    {
                        fileStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    }
                    else
                    {
                        fileStream = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    }

                    int  bytesSize;
                    long fileSize = response.ContentLength;
                    Trace.WriteLine(Trace.kCore, "fileSize=" + fileSize);
                    byte[] downloadBuffer = new byte[kPacketLength];
                    int    total          = startingPoint;

                    iUpdateProgress = (int)((total / (float)fileSize) * 100.0f);
                    if (EventUpdateProgress != null)
                    {
                        EventUpdateProgress(this, EventArgs.Empty);
                    }

                    while ((bytesSize = responseSteam.Read(downloadBuffer, 0, downloadBuffer.Length)) > 0)
                    {
                        fileStream.Write(downloadBuffer, 0, bytesSize);

                        total          += bytesSize;
                        iUpdateProgress = (int)((total / (float)fileSize) * 100.0f);

                        if (EventUpdateProgress != null)
                        {
                            EventUpdateProgress(this, EventArgs.Empty);
                        }
                    }

                    if (fileStream != null)
                    {
                        fileStream.Close();
                        fileStream.Dispose();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                string fileName = Path.Combine(iUpdateFolder, Guid.NewGuid().ToString() + ".dll");
                File.Move(tempFile, fileName);
                aInfo.FileName = fileName;
            }
            catch (Exception e)
            {
                UserLog.WriteLine(String.Format("Error downloading update: {0}", e));
                InvalidUpdateFile(aInfo);
            }
        }