2017-05-22 5 views
1

우리는 데이터베이스에서 모든 데이터를 검색하는 Click-Once WPF Windows 응용 프로그램을 개발 중입니다. 사용자가 해당 데이터를 입력 할 수있는 양식을 구현하고 SqlConnectionStringBuilder를 사용하여 연결 문자열을 작성하면 정상적으로 작동합니다..NET WPF를 사용하여 영구 사용자 연결 문자열을 저장하는 방법 Click-Once

우리는 우리가 (다른 ConfigurationUserLevel, 응용 프로그램이 충돌을 사용하는 경우

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

내가 왜 아직 모르는 사용의 ConfigurationManager에 연결 문자열을 추가,하지만 난 엔티티 프레임 워크 모델을로드하려고 생각 파일이 올바른 사용자 수준에 저장되어 있지 않기 때문에 연결 문자열을 찾지 못합니다. 이제, 우리는 별도의 파일에 연결 문자열을 저장하고 우리는 버전 제어에 그것을 확인하지 않아도의 App.config에로드 : 그것은 우리 자신이 포함되어 있기 때문에

<connectionStrings configSource="connections.config"/> 

우리는이 파일을 배포하지 않습니다 개발 연결 문자열. 오히려 사용자가 입력 한 연결 문자열이 저장 될 배포 용 빈 파일을 만듭니다. 이것은 완벽하게 작동합니다.

문제는 클릭 한번 업데이트하면 파일이 "손실"됩니다. 구성 파일에서 암호화 된 영구 사용자 별 연결 문자열을 저장하는 가장 좋은 방법은 무엇입니까? 아니면 완전히 레지스트리로 전환해야합니까? 또는 %APPDATA%/Local/Apps/2.0/...../ 폴더 외부에 암호화 된 자체 파일을 만들고 Entity Framework Context를 초기화 할 때 수동으로로드 할 수 있습니까?

+1

응용 프로그램이 충돌하는 경우 적절한 로깅을 추가하십시오. 추측하지 마십시오.개별 폴더를 적절한 폴더에 저장하면 별도의 설정 파일을 사용할 때 아무런 문제가 없습니다. 이 모든 것들은 잘 기록되어 있습니다. –

+1

자격 증명을 신경 쓰면 * 사용하지 마십시오. Windows 인증을 대신 사용하십시오. OS와 응용 프로그램은 사용자가 누구인지 이미 알고 있습니다. 질문하거나 사용자 이름을 저장할 필요가 없습니다 –

+0

안녕하세요 Panagiotis, 귀하의 조언을 주셔서 감사합니다. 우리는 현재 로깅 작업을하고 있습니다. – LeoReentry

답변

1

당신은이 코드를 아래에, 당신은 귀하의 요구 사항이 코드를 수정해야의 도움으로 당신에게

https://msdn.microsoft.com/en-us/library/dd997001.aspx 도움이 될 MSDN 사이트를 방문 할 수 있습니다,이 도움이되기를 바랍니다.

, 당신의 ClickOnce 응용 프로그램에서 사용자 정의 ClickOnce 응용 프로그램 설치를

을 만들 System.Deployment 및 System.Windows.Forms에 대한 참조를 추가합니다.

응용 프로그램에 새 클래스를 추가하고 이름을 지정하십시오. 이 연습에서는 MyInstaller라는 이름을 사용합니다.

새로운 클래스의 맨 위에 다음 가져 오기 또는 사용 문을 추가하십시오.

using System.Deployment.Application; 
using System.Windows.Forms; 

클래스에 다음 메소드를 추가하십시오.

이러한 메서드는 InPlaceHostingManager 메서드를 호출하여 배포 매니페스트를 다운로드하고 적절한 사용 권한을 지정하고 설치 권한을 사용자에게 요청한 다음 응용 프로그램을 다운로드하여 ClickOnce 캐시에 설치합니다. 사용자 지정 설치 관리자는 ClickOnce 응용 프로그램이 사전에 트러스트되도록 지정하거나 트러스트 결정을 AssertApplicationRequirements 메서드 호출로 연기 할 수 있습니다. 이 코드는 응용 프로그램을 사전 트러스트합니다. 참고 - 사전 트러스트를 통해 할당 된 권한은 사용자 지정 설치 관리자 코드의 권한을 초과 할 수 없습니다.

InPlaceHostingManager iphm = null; 

    public void InstallApplication(string deployManifestUriStr) 
    { 
     try 
     { 
      Uri deploymentUri = new Uri(deployManifestUriStr); 
      iphm = new InPlaceHostingManager(deploymentUri, false); 
     } 
     catch (UriFormatException uriEx) 
     { 
      MessageBox.Show("Cannot install the application: " + 
       "The deployment manifest URL supplied is not a valid URL. " + 
       "Error: " + uriEx.Message); 
      return; 
     } 
     catch (PlatformNotSupportedException platformEx) 
     { 
      MessageBox.Show("Cannot install the application: " + 
       "This program requires Windows XP or higher. " + 
       "Error: " + platformEx.Message); 
      return; 
     } 
     catch (ArgumentException argumentEx) 
     { 
      MessageBox.Show("Cannot install the application: " + 
       "The deployment manifest URL supplied is not a valid URL. " + 
       "Error: " + argumentEx.Message); 
      return; 
     } 

     iphm.GetManifestCompleted += new EventHandler<GetManifestCompletedEventArgs>(iphm_GetManifestCompleted); 
     iphm.GetManifestAsync(); 
    } 

    void iphm_GetManifestCompleted(object sender, GetManifestCompletedEventArgs e) 
    { 
     // Check for an error. 
     if (e.Error != null) 
     { 
      // Cancel download and install. 
      MessageBox.Show("Could not download manifest. Error: " + e.Error.Message); 
      return; 
     } 

     // bool isFullTrust = CheckForFullTrust(e.ApplicationManifest); 

     // Verify this application can be installed. 
     try 
     { 
      // the true parameter allows InPlaceHostingManager 
      // to grant the permissions requested in the applicaiton manifest. 
      iphm.AssertApplicationRequirements(true) ; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("An error occurred while verifying the application. " + 
       "Error: " + ex.Message); 
      return; 
     } 

     // Use the information from GetManifestCompleted() to confirm 
     // that the user wants to proceed. 
     string appInfo = "Application Name: " + e.ProductName; 
     appInfo += "\nVersion: " + e.Version; 
     appInfo += "\nSupport/Help Requests: " + (e.SupportUri != null ? 
      e.SupportUri.ToString() : "N/A"); 
     appInfo += "\n\nConfirmed that this application can run with its requested permissions."; 
     // if (isFullTrust) 
     // appInfo += "\n\nThis application requires full trust in order to run."; 
     appInfo += "\n\nProceed with installation?"; 

     DialogResult dr = MessageBox.Show(appInfo, "Confirm Application Install", 
      MessageBoxButtons.OKCancel, MessageBoxIcon.Question); 
     if (dr != System.Windows.Forms.DialogResult.OK) 
     { 
      return; 
     } 

     // Download the deployment manifest. 
     iphm.DownloadProgressChanged += new EventHandler<DownloadProgressChangedEventArgs>(iphm_DownloadProgressChanged); 
     iphm.DownloadApplicationCompleted += new EventHandler<DownloadApplicationCompletedEventArgs>(iphm_DownloadApplicationCompleted); 

     try 
     { 
      // Usually this shouldn't throw an exception unless AssertApplicationRequirements() failed, 
      // or you did not call that method before calling this one. 
      iphm.DownloadApplicationAsync(); 
     } 
     catch (Exception downloadEx) 
     { 
      MessageBox.Show("Cannot initiate download of application. Error: " + 
       downloadEx.Message); 
      return; 
     } 
    } 

    /* 
    private bool CheckForFullTrust(XmlReader appManifest) 
    { 
     if (appManifest == null) 
     { 
      throw (new ArgumentNullException("appManifest cannot be null.")); 
     } 

     XAttribute xaUnrestricted = 
      XDocument.Load(appManifest) 
       .Element("{urn:schemas-microsoft-com:asm.v1}assembly") 
       .Element("{urn:schemas-microsoft-com:asm.v2}trustInfo") 
       .Element("{urn:schemas-microsoft-com:asm.v2}security") 
       .Element("{urn:schemas-microsoft-com:asm.v2}applicationRequestMinimum") 
       .Element("{urn:schemas-microsoft-com:asm.v2}PermissionSet") 
       .Attribute("Unrestricted"); // Attributes never have a namespace 

     if (xaUnrestricted != null) 
      if (xaUnrestricted.Value == "true") 
       return true; 

     return false; 
    } 
    */ 

    void iphm_DownloadApplicationCompleted(object sender, DownloadApplicationCompletedEventArgs e) 
    { 
     // Check for an error. 
     if (e.Error != null) 
     { 
      // Cancel download and install. 
      MessageBox.Show("Could not download and install application. Error: " + e.Error.Message); 
      return; 
     } 

     // Inform the user that their application is ready for use. 
     MessageBox.Show("Application installed! You may now run it from the Start menu."); 
    } 

    void iphm_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
    { 
     // you can show percentage of task completed using e.ProgressPercentage 
    } 

코드로 설치를 시도하려면 InstallApplication 메서드를 호출하십시오. 예를 들어 MyInstaller 클래스의 이름을 지정한 경우 다음과 같이 InstallApplication을 호출 할 수 있습니다.

MyInstaller installer = new MyInstaller(); 
installer.InstallApplication(@"\\myServer\myShare\myApp.application"); 
MessageBox.Show("Installer object created."); 
+0

감사합니다. 매우 유용합니다. 나는 그걸 들여다 볼게! – LeoReentry