public AudioDeviceSessionCollection(IAudioDevice parent, IMMDevice device)
        {
            Trace.WriteLine($"AudioDeviceSessionCollection Create dev={device.GetId()}");

            _parent     = new WeakReference <IAudioDevice>(parent);
            _dispatcher = App.Current.Dispatcher;

            Task.Factory.StartNew(() =>
            {
                try
                {
                    _sessionManager = device.Activate <IAudioSessionManager2>();
                    _sessionManager.RegisterSessionNotification(this);
                    var enumerator = _sessionManager.GetSessionEnumerator();
                    int count      = enumerator.GetCount();
                    for (int i = 0; i < count; i++)
                    {
                        CreateAndAddSession(enumerator.GetSession(i));
                    }
                }
                catch (Exception ex)
                {
                    AppTrace.LogWarning(ex);
                }
            });
        }
        private void CreateAndAddSession(IAudioSessionControl session)
        {
            try
            {
                if (!_parent.TryGetTarget(out IAudioDevice parent))
                {
                    throw new Exception("Device session parent is invalid but device is still notifying.");
                }

                var newSession = new AudioDeviceSession(parent, session);
                _dispatcher.BeginInvoke((Action)(() =>
                {
                    if (newSession.State == SessionState.Moved)
                    {
                        _movedSessions.Add(newSession);
                        newSession.PropertyChanged += MovedSession_PropertyChanged;
                    }
                    else
                    {
                        AddSession(newSession);
                    }
                }));
            }
            catch (ZombieProcessException ex)
            {
                // No need to log these to the cloud, but the debug output
                // can still be helpful for troubleshooting.
                Trace.TraceError($"{ex}");
            }
            catch (Exception ex)
            {
                AppTrace.LogWarning(ex);
            }
        }
Esempio n. 3
0
        private void LoadIconResources()
        {
            var originalIcon = new Icon(Application.GetResourceStream(new Uri("pack://application:,,,/EarTrumpet;component/Assets/Tray.ico")).Stream);

            try
            {
                _icons.Add(IconId.OriginalIcon, originalIcon);
                _icons.Add(IconId.NoDevice, GetIconFromFile(_trayIconPath, (int)IconId.NoDevice));
                _icons.Add(IconId.Muted, GetIconFromFile(_trayIconPath, (int)IconId.Muted));
                _icons.Add(IconId.SpeakerZeroBars, GetIconFromFile(_trayIconPath, (int)IconId.SpeakerZeroBars));
                _icons.Add(IconId.SpeakerOneBar, GetIconFromFile(_trayIconPath, (int)IconId.SpeakerOneBar));
                _icons.Add(IconId.SpeakerTwoBars, GetIconFromFile(_trayIconPath, (int)IconId.SpeakerTwoBars));
                _icons.Add(IconId.SpeakerThreeBars, GetIconFromFile(_trayIconPath, (int)IconId.SpeakerThreeBars));
            }
            catch (Exception ex)
            {
                AppTrace.LogWarning(ex);

                _icons.Clear();
                _icons.Add(IconId.OriginalIcon, originalIcon);
                _icons.Add(IconId.NoDevice, originalIcon);
                _icons.Add(IconId.Muted, originalIcon);
                _icons.Add(IconId.SpeakerZeroBars, originalIcon);
                _icons.Add(IconId.SpeakerOneBar, originalIcon);
                _icons.Add(IconId.SpeakerTwoBars, originalIcon);
                _icons.Add(IconId.SpeakerThreeBars, originalIcon);
            }
        }
Esempio n. 4
0
        private static PandaPacket getLabelDataResponse(string clientID, PandaPacket request)
        {
            //
            PandaPacket response = null;
            DataSet     ds       = null;

            try {
                //Extract message body
                string barcode1 = request.MessageBody.Substring(0, 32).TrimEnd();
                string barcode2 = request.MessageBody.Substring(32, 32).TrimEnd();
                string barcode3 = request.MessageBody.Substring(64, 32).TrimEnd();
                string barcode4 = request.MessageBody.Substring(96, 32).TrimEnd();
                string barcode5 = request.MessageBody.Substring(128, 32).TrimEnd();
                string barcode6 = request.MessageBody.Substring(160, 32).TrimEnd();
                float  weight   = Convert.ToInt32(request.MessageBody.Substring(192, 5)) / 100;

                //Process the label data request
                ds = CartonMgr.ProcessLabelDataRequest(barcode1, barcode2, barcode3, barcode4, barcode5, barcode6, weight);
                if (ds != null)
                {
                    //New carton
                    response = PandaPacket.Encode(clientID, RESPONSE_LABELDATA, request, 0, 1, PandaPacket.FormatLabelDataMessageBody(ds.Tables["PandATable"].Rows[0]["CartonID"].ToString(), int.Parse(ds.Tables["PandATable"].Rows[0]["StatusCode"].ToString()), ds.Tables["PandATable"].Rows[0]["LabelData"].ToString()));
                }
            }
            catch (Exception ex) {
                AppTrace.Instance().TheTrace.WriteLine(new TraceMessage("Error occurred while processing request for label data- " + ex.ToString(), AppLib.EVENTLOGNAME, LogLevel.Error, "PacketMgr"));
                if (ds != null)
                {
                    response = PandaPacket.Encode(clientID, RESPONSE_LABELDATA, request, 0, 1, PandaPacket.FormatLabelDataMessageBody(ds.Tables["PandATable"].Rows[0]["CartonID"].ToString(), int.Parse(ds.Tables["PandATable"].Rows[0]["StatusCode"].ToString()), ds.Tables["PandATable"].Rows[0]["LabelData"].ToString()));
                }
            }
            return(response);
        }
Esempio n. 5
0
        internal static void Initialize()
        {
            AppTrace.Initialize(OnWarningException);

            try
            {
                Application.Current.Exit += (_, __) => _isAppShuttingDown = true;
#if DEBUG
                WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey");
#endif

                WPFClient.Config.StoreOfflineErrors = true;
                WPFClient.Config.AppVersion         = App.Current.GetVersion().ToString();
                WPFClient.Start();

                WPFClient.Config.BeforeNotify(OnBeforeNotify);

                Task.Factory.StartNew(WPFClient.SendStoredReports);
            }
            catch (Exception ex)
            {
                // No point in AppTrace.LogWarning here because bugsnag is broken.
                Trace.WriteLine(ex);
            }
        }
Esempio n. 6
0
        private void MoveAppToDeviceInternal(IAppItemViewModel app, DeviceViewModel dev)
        {
            var searchId = dev?.Id;

            if (dev == null)
            {
                searchId = _deviceManager.DefaultPlaybackDevice.Id;
            }
            DeviceViewModel oldDevice = AllDevices.First(d => d.Apps.Contains(app));
            DeviceViewModel newDevice = AllDevices.First(d => searchId == d.Id);

            try
            {
                bool isLogicallyMovingDevices = (oldDevice != newDevice);

                var tempApp = new TemporaryAppItemViewModel(app);

                app.MoveToDevice(dev?.Id, hide: isLogicallyMovingDevices);

                // Update the UI if the device logically changed places.
                if (isLogicallyMovingDevices)
                {
                    oldDevice.AppVirtuallyLeavingFromThisDevice(app);
                    newDevice.AppVirtuallMovingToThisDevice(tempApp);
                }
            }
            catch (Exception ex)
            {
                AppTrace.LogWarning(ex);
            }
        }
Esempio n. 7
0
 static void Main(string[] args)
 {
     AppTrace.AddListener(new ColorConsoleTraceListener {
         TraceOutputOptions = System.Diagnostics.TraceOptions.None
     });
     Application.Run(args);
 }
Esempio n. 8
0
        static string ReadSetting(string key)
        {
            string ret = null;

            if (App.Current.HasIdentity())
            {
                try
                {
                    ret = (string)Windows.Storage.ApplicationData.Current.LocalSettings.Values[key];
                }
                catch (Exception ex)
                {
                    Trace.TraceError($"{ex}");
                    AppTrace.LogWarning(ex);
                    return(ret);
                }
            }
            else
            {
                using (var regKey = Registry.CurrentUser.CreateSubKey(@"Software\EarTrumpet", true))
                {
                    ret = (string)regKey.GetValue(key);
                }
            }

            return(ret);
        }
Esempio n. 9
0
        public static void DumpAndShowData()
        {
            var allText = DumpDevices(WindowsAudioFactory.Create(AudioDeviceKind.Playback));

            allText += DumpDevices(WindowsAudioFactory.Create(AudioDeviceKind.Recording));
            allText += Environment.NewLine;
            allText += $"App: {App.Current.GetVersion()}" + Environment.NewLine;
            allText += $"HasIdentity: {App.Current.HasIdentity()}" + Environment.NewLine;
            allText += $"CurrentCulture: {CultureInfo.CurrentCulture.Name}" + Environment.NewLine;
            allText += $"CurrentUICulture: {CultureInfo.CurrentUICulture.Name}" + Environment.NewLine;
            allText += $"BuildLabel: {SystemSettings.BuildLabel}" + Environment.NewLine;
            allText += $"Loaded Addons: {string.Join(" ", Extensibility.Hosting.AddonManager.Current.All.Select(a => a.DisplayName))}" + Environment.NewLine;
            allText += $"IsLightTheme: {SystemSettings.IsLightTheme}" + Environment.NewLine;
            allText += $"IsSystemLightTheme: {SystemSettings.IsSystemLightTheme}" + Environment.NewLine;
            allText += $"RTL: {SystemSettings.IsRTL}" + Environment.NewLine;
            allText += $"IsTransparencyEnabled: {SystemSettings.IsTransparencyEnabled}" + Environment.NewLine;
            allText += $"UseAccentColor: {SystemSettings.UseAccentColor}" + Environment.NewLine;
            allText += $"AnimationsEnabled: {SystemParameters.MenuAnimation}" + Environment.NewLine;
            allText += Environment.NewLine;
            allText += AppTrace.GetLogText();

            var fileName = $"{Path.GetTempFileName()}.txt";

            File.WriteAllText(fileName, allText);
            ProcessHelper.StartNoThrow(fileName);
        }
Esempio n. 10
0
        public ProjectionContext Transform(ProjectionContext context)
        {
            var modelManager = InputManager;

            var model = modelManager.Get(context.Input.Selector);
            if (model != null)
            {
                var input = new ProjectionInput(model);

                // this the generator impl

                GeneratorRegistry.TryGet(context.GeneratorName, out GeneratorDeclaration generatorDecl);

                var transformationRules = generatorDecl.Rules;

                var transformationOutput = new ModelToTextOutput();

                foreach (var tranformationRule in transformationRules)
                {
                    var templateEngine = TemplateEngineProvider.GetEngine(tranformationRule.TemplateLanguage);
                    var transformationOutputFile = templateEngine.Transform(context, input, tranformationRule);
                    transformationOutput.AddOutputFile(transformationOutputFile);
                }

                // end gen impl

                context.Output = transformationOutput;

                AppTrace.Information("Projection completed.");
            }

            return context;
        }
Esempio n. 11
0
        private static void SetInternal(IntPtr handle, User32.AccentState accentState, bool showBorders = false, uint tintOpacity = 0)
        {
            var accent = new User32.AccentPolicy
            {
                AccentState   = accentState,
                AccentFlags   = (showBorders) ? User32.AccentFlags.DrawAllBorders : User32.AccentFlags.None,
                GradientColor = (_defaultTintOpacity << 24) | (_defaultTintBackgroundColor & 0xFFFFFF)
            };

            var accentStructSize = Marshal.SizeOf(accent);

            var accentPtr = Marshal.AllocHGlobal(accentStructSize);

            Marshal.StructureToPtr(accent, accentPtr, false);

            var data = new User32.WindowCompositionAttribData();

            data.Attribute  = User32.WindowCompositionAttribute.WCA_ACCENT_POLICY;
            data.SizeOfData = accentStructSize;
            data.Data       = accentPtr;

            var ret = User32.SetWindowCompositionAttribute(handle, ref data);

            AppTrace.LogWarningIfFailed(ret);
            Debug.Assert(ret == 0 || ret == 1);

            Marshal.FreeHGlobal(accentPtr);
        }
Esempio n. 12
0
        public static bool HasIdentity(this Application app)
        {
#if VSDEBUG
            if (Debugger.IsAttached)
            {
                return(false);
            }
#endif

            if (_hasIdentity == null)
            {
                try
                {
                    _hasIdentity = (Package.Current.Id != null);
                }
                catch (InvalidOperationException ex)
                {
#if !DEBUG
                    // We do not expect this to occur in production when the app is packaged.
                    AppTrace.LogWarning(ex);
#else
                    Trace.WriteLine(ex);
#endif
                    _hasIdentity = false;
                }
            }

            return((bool)_hasIdentity);
        }
Esempio n. 13
0
        protected override int OnExecute(CommandOptions options)
        {
            var generateOptions = (GenerateOptions)options;

            var projectFile = Path.Combine(Environment.CurrentDirectory, "shapeflow.config.json");

            if (File.Exists(projectFile) && string.IsNullOrWhiteSpace(generateOptions.ProjectFile))
            {
                generateOptions.ProjectFile = projectFile;
            }

            try
            {
                var parameters = new Dictionary <string, string>
                {
                    { "project-root", Environment.CurrentDirectory }
                };

                var solution = Solution.ParseFile(generateOptions.ProjectFile);
                solution.AddParameters(parameters);
                solution.AddParameters(generateOptions.Parameters);

                var ev     = new SolutionEventContext(solution);
                var engine = _container.Resolve <SolutionEngine>();

                engine.Run(ev);
            }
            catch (ApplicationOptionException ex)
            {
                AppTrace.Error("Invalid command line arguments. See exception for details.", ex);
                Console.WriteLine(ex.Message);
            }

            return(0);
        }
Esempio n. 14
0
        public ModelContext LoadModel(ModelDeclaration declaration)
        {
            var result = new EntityModelRoot();

            var tableName = declaration.GetParameter("tableName");

            var databaseInfo = new DatabaseInfo
            {
                Server   = declaration.GetParameter("server"),
                Name     = declaration.GetParameter("db"),
                User     = declaration.GetParameter("user"),
                Password = declaration.GetParameter("password")
            };

            var query = TableMetadataQuery;

            AppTrace.Verbose($"Loading metadata from database {databaseInfo.Name} on {databaseInfo.Server} instance.");

            if (!string.IsNullOrWhiteSpace(tableName))
            {
                query = string.Concat(query, " and tbl.TABLE_NAME = @TableName");
            }

            using (var connection = new SqlConnection(SqlHelper.GetConnectionString(databaseInfo)))
            {
                var lines   = connection.Query <DbObjectLine>(TableMetadataQuery, new { TableName = tableName });
                var grouped = lines.GroupBy(l => l.ObjectName);
                foreach (var g in grouped)
                {
                    var m = new EntityModel
                    {
                        ObjectName = SafeName(g.Key)
                    };

                    m.AddProperties(g.OrderBy(p => p.PropertyPosition).Select(p => new PropertyModel
                    {
                        DateTimePrecision      = p.DateTimePrecision,
                        PropertyDefaultValue   = p.PropertyDefaultValue,
                        PropertyLength         = p.PropertyLength,
                        PropertyName           = p.PropertyName,
                        PropertyPosition       = p.PropertyPosition,
                        PropertyPrecision      = p.PropertyPrecision,
                        PropertyPrecisionRadix = p.PropertyPrecisionRadix,
                        PropertySqlDataType    = p.PropertySqlDataType,
                        Scale         = p.Scale,
                        SqlIsNullable = p.SqlIsNullable
                    }));

                    result.AddModels(new[] { m });
                }
            }

            AppTrace.Verbose($"Loaded { result.Entities.Count() } models.");

            return(new ModelContext(declaration, new DbModel(result, ModelFormat.Clr, declaration.ModelName, declaration.Tags)));
        }
Esempio n. 15
0
        public bool ValidateArguments(ModelDeclaration context)
        {
            if (string.IsNullOrWhiteSpace(context.GetParameter(ModelPathParameter)))
            {
                // TODO: this should be a validation service
                AppTrace.Error($"The parameter {ModelPathParameter} is required.");
                return(false);
            }

            return(true);
        }
        private bool DeleteInstanceInternal(IComparable instanceId, bool replicate, long evictionVersion)
        {
            Requires.Argument("instanceId", instanceId).NotNull();

            StatefulServiceExecutionContext executionContext = StatefulServiceExecutionContext.Current as StatefulServiceExecutionContext;

            if (executionContext == null || executionContext.Partition == null)
            {
                throw new InvalidOperationException("Program instance cannot be obtained outside context of a partition. Please ensure that StatefulServiceReplicaT.Invoke is called.");
            }

            StatefulProgramInstance instance = null;
            ItemCollection <IComparable, StatefulProgramInstance> instances;

            using (this.instanceManager.GetInstances(LockPermission.Write, out instances))
            {
                if (instances.Contains(instanceId))
                {
                    instance = (StatefulProgramInstance)instances[instanceId];
                    if (evictionVersion != -2 && !instance.CanEvict(evictionVersion))
                    {
                        return(false);
                    }

                    instances.Remove(instanceId);
                    ((IDisposable)instance).Dispose();
                }
            }

            if (instance != null)
            {
                if (replicate)
                {
                    Replicable <StatefulProgramInstance> replicable = new Replicable <StatefulProgramInstance>(instance.Id.ToString(), instance);
                    ReplicationScope replicationScope = new ReplicationScope(new Replicable[] { replicable }, ReplicationOperationType.Evict);
                    replicationScope.ReplicateAsync().ContinueWith(
                        task =>
                    {
                        ReplicationResult result = task.IsFaulted ? ReplicationResult.Failed : task.Result;
                        if (result != ReplicationResult.Success)
                        {
                            AppTrace.TraceMsg(TraceLogEventType.Warning, "StatefulServiceReplicaT.DeleteInstanceInternal", "Replication call to dispose the instance with id {0} failed.", instance.Id);
                        }
                    },
                        TaskContinuationOptions.ExecuteSynchronously);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
 private static void Set <T>(string key, T value)
 {
     try
     {
         Windows.Storage.ApplicationData.Current.LocalSettings.Values[key] = value;
     }
     catch (Exception ex)
     {
         Trace.TraceError($"{ex}");
         AppTrace.LogWarning(ex);
     }
 }
Esempio n. 18
0
 internal static IDisposable StartNoThrowAndLogWarning(string fileName)
 {
     try
     {
         return(Process.Start(fileName));
     }
     catch (Exception ex)
     {
         AppTrace.LogWarning(ex);
     }
     return(null);
 }
 static void WriteSetting <T>(string key, T value)
 {
     try
     {
         Windows.Storage.ApplicationData.Current.LocalSettings.Values[key] = value;
     }
     catch (Exception ex)
     {
         // Windows Bug: Windows Storage APIs are still unreliable
         AppTrace.LogWarning(ex);
     }
 }
 private static T Get <T>(string key)
 {
     try
     {
         return((T)Windows.Storage.ApplicationData.Current.LocalSettings.Values[key]);
     }
     catch (Exception ex)
     {
         Trace.TraceError($"{ex}");
         AppTrace.LogWarning(ex);
     }
     return(default(T));
 }
 private static bool HasKey(string key)
 {
     try
     {
         return(Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey(key));
     }
     catch (Exception ex)
     {
         Trace.TraceError($"{ex}");
         AppTrace.LogWarning(ex);
     }
     return(false);
 }
        public List <Course> Get()
        {
            List <Course> retVal = new List <Course>();

            try {
                retVal = context.Courses.ToList <Course>();
            } catch (Exception ex) {
                AppTrace.Error(ex.Message);
                throw;
            }

            return(retVal);
        }
        public Course Get(int id)
        {
            Course retVal = null;

            try {
                retVal = context.Courses.Where(c => c.Id == id).FirstOrDefault();
            } catch (Exception ex) {
                AppTrace.Error(ex.Message);
                throw;
            }

            return(retVal);
        }
Esempio n. 24
0
        private static PandaPacket getHeartbeatResponse(string clientID, PandaPacket request)
        {
            //Reply with a heartbeat signal
            PandaPacket response = null;

            try {
                response = PandaPacket.Encode(clientID, RESPONSE_HEARTBEAT, request, 0, 1, "");
            }
            catch (Exception ex) {
                AppTrace.Instance().TheTrace.WriteLine(new TraceMessage("An error occurred while processing request for heartbeat." + ex.ToString(), AppLib.EVENTLOGNAME, LogLevel.Error, "PacketMgr"));
            }
            return(response);
        }
Esempio n. 25
0
        public List <Student> Get()
        {
            List <Student> retVal = new List <Student>();

            try {
                //find the object in the database
                retVal = context.Students.ToList <Student>();
            } catch (Exception ex) {
                AppTrace.Error(ex.Message);
                throw;
            }

            return(retVal);
        }
        public bool HasKey(string key)
        {
            var ret = false;

            try
            {
                ret = Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey(key);
            }
            catch (Exception ex)
            {
                AppTrace.LogWarning(ex);
            }
            return(ret);
        }
Esempio n. 27
0
        public Student Get(int id)
        {
            Student retVal = null;

            try {
                //find the object in the database
                retVal = context.Students.Where(c => c.Id == id).FirstOrDefault();
            } catch (Exception ex) {
                AppTrace.Error(ex.Message);
                throw;
            }

            return(retVal);
        }
Esempio n. 28
0
        public void PerformWrite(string outputFileName, string outputText)
        {
            outputFileName = GetWritePath(outputFileName);

            var outputDirectory = Path.GetDirectoryName(outputFileName);

            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            AppTrace.Information("Writing file '{0}'", outputFileName);

            File.WriteAllText(outputFileName, outputText);
        }
        static T ReadSetting <T>(string key)
        {
            T ret = default(T);

            try
            {
                ret = (T)Windows.Storage.ApplicationData.Current.LocalSettings.Values[key];
            }
            catch (Exception ex)
            {
                // Windows Bug: Windows Storage APIs are still unreliable
                AppTrace.LogWarning(ex);
            }
            return(ret);
        }
Esempio n. 30
0
        public static string GetDefaultEndPoint(int processId)
        {
            try
            {
                EnsurePolicyConfig();

                s_sharedPolicyConfig.GetPersistedDefaultAudioEndpoint((uint)processId, EDataFlow.eRender, ERole.eMultimedia | ERole.eConsole, out string deviceId);
                return(UnpackDeviceId(deviceId));
            }
            catch (Exception ex)
            {
                AppTrace.LogWarning(ex);
            }

            return(null);
        }