Ответы пользователя по тегу C#
  • Как сделать обратную функцию этой?

    artem_b89
    @artem_b89
    Сетевой бездельник
    Как-то так. Нужно будет немного допилить напильником
    public static string Back(string input)
    {
    StringBuilder result = new StringBuilder();
    var sp = input.Split(' ');
    for (int i = 0; i < sp.Length; i++)
    {
    if (String.IsNullOrWhiteSpace(sp[i])) continue;
    var b=byte.Parse(sp[i], System.Globalization.NumberStyles.AllowHexSpecifier);
    char ch = (char)b;
    result.Append(ch);
    }
    return result.ToString();
    }
    Ответ написан
  • Как работать с windows service?

    artem_b89
    @artem_b89
    Сетевой бездельник
    Пробуйте подключить WinDBG на старте сервиса, собрать дамп и его уже исследовать.
    Сделать это можно как написано тут:
    Configure a service to start with the WinDbg debugger attached
    You can use this method to debug services if you want to troubleshoot service-startup-related problems.
    Configure the "Image File Execution" options. To do this, use one of the following methods:
    Method 1: Use the Global Flags Editor (gflags.exe)
    Start Windows Explorer.
    Locate the gflags.exe file on your computer.

    Note The gflags.exe file is typically located in the following directory: C:\Program Files\Debugging Tools for Windows.
    Run the gflags.exe file to start the Global Flags Editor.
    In the Image File Name text box, type the image name of the process that hosts the service that you want to debug. For example, if you want to debug a service that is hosted by a process that has MyService.exe as the image name, type MyService.exe.
    Under Destination, click to select the Image File Options option.
    Under Image Debugger Options, click to select the Debugger check box.
    In the Debugger text box, type the full path of the debugger that you want to use. For example, if you want to use the WinDbg debugger to debug a service, you can type a full path that is similar to the following: C:\Program Files\Debugging Tools for Windows\windbg.exe
    Click Apply, and then click OK to quit the Global Flags Editor.
    Method 2: Use Registry Editor
    Click Start, and then click Run. The Run dialog box appears.
    In the Open box, type regedit, and then click OK to start Registry Editor.
    Important This section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly. Therefore, make sure that you follow these steps carefully. For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs. For more information about how to back up and restore the registry, click the following article number to view the article in the Microsoft Knowledge Base:
    322756 How to back up and restore the registry in Windows

    In Registry Editor, locate, and then right-click the following registry subkey:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
    Point to New, and then click Key. In the left pane of Registry Editor, notice that New Key #1 (the name of a new registry subkey) is selected for editing.
    Type ImageName to replace New Key #1, and then press ENTER.

    Note ImageName is a placeholder for the image name of the process that hosts the service that you want to debug. For example, if you want to debug a service that is hosted by a process that has MyService.exe as the image name, type MyService.exe.
    Right-click the registry subkey that you created in step e.
    Point to New, and then click String Value. In the right pane of Registry Editor, notice that New Value #1, the name of a new registry entry, is selected for editing.
    Replace New Value #1 with Debugger, and then press ENTER.
    Right-click the Debugger registry entry that you created in step h, and then click Modify. The Edit String dialog box appears.
    In the Value data text box, type DebuggerPath, and then click OK.

    Note DebuggerPath is a placeholder for the full path of the debugger that you want to use. For example, if you want to use the WinDbg debugger to debug a service, you can type a full path that is similar to the following:
    C:\Progra~1\Debugg~1\windbg.exe

    А также пишите логи, для этого могу рекомендовать log4net.

    Также на хабре были статьи:
    habrahabr.ru/post/127828
    habrahabr.ru/post/89220
    Ответ написан
    Комментировать
  • Как при помощи триггера в WPF изменить картинку в дочернем элементе ListBox?

    artem_b89
    @artem_b89
    Сетевой бездельник
    Попробуйте так
    <Image Width="22"
                                   Height="22"
                                   Margin="5"
                                    >
                                <Image.Style>
                                    <Style>
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBoxItem}}" Value="true">
                                                <Setter Property="Image.Source" Value="../Images/play2.png"/>
                                            </DataTrigger>
                                            <DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBoxItem}}" Value="false">
                                                <Setter Property="Image.Source" Value="../Images/play.png"/>
                                            </DataTrigger>
                                        </Style.Triggers>
                                    </Style>                                
                                </Image.Style>
                            </Image>
    Ответ написан
    Комментировать
  • Как изменить public переменную из другой страницы (WPF)?

    artem_b89
    @artem_b89
    Сетевой бездельник
    Оператор new создаёт новый экземпляр класса. Советую взять книжку по программированию на C# и прочитать, а лучше даже две:
    Сначала www.ozon.ru/context/detail/id/3658608
    Потом www.ozon.ru/context/detail/id/21236101

    По поводу вашего вопроса, уже отвечал: Использовать статический класс или синглтон.
    Вот пример синглтона:
    public class CurrentContext
        {
            private CurrentContext()
            {
                
            }
            
            private static Lazy<CurrentContext> instance = new Lazy<CurrentContext>(() => new CurrentContext());
            
            public static CurrentContext Instance
            {
                get { return instance.Value; }
            }
            
            public string Text {get;set;}
        }

    Теперь к свойству Text можно обращаться, например так:
    CurrentContext.Instance.Text="тест";

    Вот еще пример приложения : https://dl.dropboxusercontent.com/u/18441732/test/...
    Ответ написан
    Комментировать
  • Как в C# WPF сохранить данные (Сессии, roamingSettings или подобное)?

    artem_b89
    @artem_b89
    Сетевой бездельник
    Использовать статический класс или синглтон.

    P.S.
    Вообще, для разработки под WPF рекомендовал бы посмотреть что такое MVVM, IoC, DI, Singlton и как это всё сделать на C#.
    Ответ написан
    3 комментария
  • Как добавить в ресурсы папку с изображениями в WPF?

    artem_b89
    @artem_b89
    Сетевой бездельник
    Чтобы использовать изображения в приложении, не обязательно добавлять их в ресурсы, тем более если они будут добавляться и удаляться. Допустим в вашей форме есть контрол Image с именем Pict, тогда чтобы отобразить в нем некоторую картинку можно использовать следующий пример:
    using System;
    using System.Windows;
    using System.Windows.Media.Imaging;
    using System.Reflection;
    using FilePath=System.IO.Path;
    namespace WpfApplication1
    {
    public partial class MainWindow : Window
    {
    public MainWindow()
    {
    InitializeComponent();
    var directory=FilePath.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    Pict.Source = new BitmapImage(new Uri(FilePath.Combine(directory, "uploads/2015/logo.jpg")));
    }
    }
    }
    Ответ написан
  • Как в WPF программно скрыть Button, а потом снова отобразить?

    artem_b89
    @artem_b89
    Сетевой бездельник
    У UI элементов есть свойство visibility. Соответственно при нажатии на кнопку нужно менять это свойство нужного элемента. https://msdn.microsoft.com/ru-ru/library/system.wi...(v=vs.110).aspx
    Ответ написан
    Комментировать
  • Как лучше реализовать сервис?

    artem_b89
    @artem_b89
    Сетевой бездельник
    Чтобы не городить велосипед, могу предложить использовать WCF
    Ответ написан
    1 комментарий
  • Запросы к SQL Server в Visual Studio как вывести результат в WPF?

    artem_b89
    @artem_b89
    Сетевой бездельник
    Здравствуйте.
    Для работы с БД рекомендую использовать Entity Framework, он достаточно прост в освоении, в интернете много информации по его использованию, например metanit.com/sharp/entityframework/index.php
    Для WPF приложения лучше использовать паттерн MVVM, по его использованию также много информации, например professorweb.ru/my/WPF/documents_WPF/level36/36_5.php
    Ответ написан
    Комментировать