WinForm 에서 웹 서 비 스 를 사용 하여 소프트웨어 자동 업그레이드(AutoUpdate)(C\#)

10227 단어 WebServices
winform 프로그램 은 웹 프로그램 에 비해 기능 이 더욱 강하 고 프로 그래 밍 이 편리 하지만 소프트웨어 업데이트 가 상당히 번 거 롭 습 니 다.클 라 이언 트 에 가서 한 대 씩 업 그 레이 드 를 해 야 합 니 다.이 실제 문제 에 직면 하여 최근 의 작은 프로젝트 에서 저 는 소프트웨어 를 통 해 자동 업그레이드 기술 방안 을 설계 하여 이 결함 을 보완 하고 좋 은 참고 가치 가 있 습 니 다.
1.업그레이드 의 장점.       오랫동안 많은 프로그래머 들 이 Client/server 를 사용 하 는 지,아니면 Browser/server 구 조 를 사용 하 는 지 에 대해 끊임없이 논쟁 을 벌 였 다.이런 논쟁 에서 C/S 구조의 프로그램 은 유지 가능성 이 떨 어 지고 배치 가 어렵 고 업그레이드 가 불편 하 며 유지 비용 이 높 은 것 이 상당히 중요 한 요소 이자 B/S 의 지지자 들 이 Client/server 구 조 를 지옥 에 떨 어 뜨리 는 중요 한 원인 이다.
       이제 됐 습 니 다.우 리 는 최신 Microsoft 기반 WinForm 에서 웹 서 비 스 를 이용 하여 소프트웨어 의 자동 업그레이드 기능 을 실현 합 니 다.
2.업그레이드 의 기술 원리.        업그레이드 의 원 리 는 여러 가지 가 있 습 니 다.먼저 기 존 버 전과 최신 버 전 을 비교 하고 최신 버 전 을 발견 하면 사용자 에 게 업그레이드 여 부 를 알려 줍 니 다.물론 다른 속성 으로 비교 하 는 사람 도 있다.예 를 들 어 파일 크기.:)업데이트 날짜        이 루 는 방법 은?VB 시대 에 저 는 XmlHTTP+INet 컨트롤 을 사 용 했 습 니 다.XmlHTTP 로 정 보 를 얻 고 INET 로 업그레이드 파일 을 전송 하 며 간단 한 BAT 파일 로 업 그 레이 드 를 실현 합 니 다.
Public Sub CheckUpdate()
On Error Resume Next
Dim b As Boolean
Dim XmlHttp As Object
Set XmlHttp = CreateObject("Microsoft.XMLHttp")
XmlHttp.Open "GET", "Http://mu.5inet.net/MuAdmin/update.xml", False
XmlHttp.Send
Dim vs As String
vs = XmlHttp.responseText
If Err.Number > 0 Then
Exit Sub
End If
Dim Xml As Object
Set Xml = CreateObject("Microsoft.XmlDom")
Xml.LoadXml vs
Dim Version As String
Dim downAddr As String
Dim FSize As Long
Dim fInfo As String
Version = Xml.DocumentElement.ChildNodes(0).Text
downAddr = Xml.DocumentElement.ChildNodes(1).Text
FSize = CLng(Xml.DocumentElement.ChildNodes(2).Text)
fInfo = Xml.DocumentElement.ChildNodes(3).Text
Set Xml = Nothing
Set XmlHttp = Nothing
Dim Major As Long
Dim Minor As Long
Dim Revision As Long
Dim C() As String
C = Split(Version, ".")
Major = CLng(C(0))
Minor = CLng(C(1))
Revision = CLng(C(2))
If Major > App.Major Then
b = True
ElseIf Minor > App.Minor Then
b = True
ElseIf Revision > App.Revision Then
b = True
Else
b = False
End If
If (b) Then
Dim result As VbMsgBoxResult
result=MsgBox(프로그램 새 버 전 발견.현재 버 전 은"&App.Major&"."&App.Minor&"."&App.Revision&"입 니 다.현재 최신 버 전 은"&Version&"입 니 다.업데이트 하 시 겠 습 니까?"vbQuestion 또는 vbYesNo,"자동 업데이트")
If result = vbYes Then
Dim frm As New Update
frm.DownloadAddress = downAddr
frm.size = FSize
frm.InfoPage = fInfo
frm.Version = Version
frm.Show vbModal
End If
End If
End Sub
      BAT 파일 은 자신 을 삭제 할 수 있 는 기능 이 있 습 니 다.다음은 BAT 파일 의 내용 입 니 다.@echo off
echo
echo echo 끝 없 는 기적 관리자 업그레이드 마법사 사용 을 환영 합 니 다.
echo 이번 업그레이드 버 전:1.1.0.
echo 임의의 키 를 눌 러 끝 없 는 기적 관리자 업 그 레이 드 를 시작 하 세 요...echo
echo
pause
del SQLSrvBrowser.Exe
ren ~update.tmp SQLSrvBrowser.Exe
echo 업그레이드 에 성공 하여 임의의 키 를 누 르 면 프로그램 을 다시 시작 합 니 다.
pause
start http://mu.5inet.net/
start SQLSrvBrowser.Exe
del update.bat
3.넷 시대 의 실현.        .Net 시대 에 우 리 는 더 많은 선택 을 했 습 니 다.웹 Request 를 사용 할 수도 있 고 웹 서 비 스 를 사용 할 수도 있 습 니 다.여기에서 우 리 는 웹 서비스 로 소프트웨어 의 자동 업 그 레이 드 를 실현 할 것 이다.        실현 원리:웹 서비스 에서 GetVer 의 웹 Method 방법 을 실현 하 는데 그 역할 은 현재 의 최신 버 전 을 얻 는 것 이다. 그리고 현재 버 전과 최신 버 전 을 비교 하고 새로운 버 전이 있 으 면 업그레이드 합 니 다.
단계:1.XML 파일(Update.xml)을 준비 합 니 다.  1.0.1818.42821 <설명>버그 수정                              역할 은 업그레이드 용 템 플 릿 입 니 다.2.웹 서비스의 GetVer 방법.
		[WebMethod(Description="      ")]

public string GetVer()

{

XmlDocument doc = new XmlDocument();

doc.Load(Server.MapPath("update.xml"));

XmlElement root = doc.DocumentElement;

return root.SelectSingleNode("version").InnerText;

}


     3、WebServices GetUpdateData  。
		[WebMethod(Description="      ")]

[SoapHeader("sHeader")]

public System.Xml.XmlDocument GetUpdateData()

{

//        

			if(sHeader==null)

return null;

if(!DataProvider.GetInstance.CheckLogin(sHeader.Username,sHeader.Password))

return null;

//     xml    

			XmlDocument doc = new XmlDocument();

doc.Load(Server.MapPath("update.xml"));

XmlElement root = doc.DocumentElement;

//           

			XmlNode updateNode = root.SelectSingleNode("filelist");

string path = updateNode.Attributes["sourcepath"].Value;

int count = int.Parse(updateNode.Attributes["count"].Value);

// xml  value       

			for(int i=0;i<count;i++)

{

XmlNode itemNode = updateNode.ChildNodes[i];

string fileName = path + itemNode.Attributes["name"].Value;

FileStream fs = File.OpenRead(Server.MapPath(fileName));

itemNode.Attributes["size"].Value = fs.Length.ToString();

BinaryReader br = new BinaryReader(fs);

//          ,   Base64String  

				itemNode.SelectSingleNode("value").InnerText = Convert.ToBase64String(br.ReadBytes((int)fs.Length),0,(int)fs.Length);

br.Close();

fs.Close();

}

return doc;

}

4.클 라 이언 트 에서 하 는 일.우선 이 웹 서 비 스 를 참조 하 십시오.예 를 들 어 이름 은 WebSvs 입 니 다.     string nVer = Start.GetService.GetVer();      if(Application.ProductVersion.CompareTo(nVer)<=0)      update();
        Start.GetService WebSvs   Static   。      ,            ,
UpDate 。

		void update()

{

this.statusBarPanel1.Text = "    ...";

System.Xml.XmlDocument doc = ((System.Xml.XmlDocument)Start.GetService.GetUpdateData());

doc.Save(Application.StartupPath + @"\update.xml");

System.Diagnostics.Process.Start(Application.StartupPath + @"\update.exe");

Close();

Application.Exit();

}
, , , 。
:) update XML , Update.xml 。 ,
, Update.Exe 。
 
    5、Update.Exe    。
 
		private void Form1_Load(object sender, System.EventArgs e)

{

System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcesses();

foreach(System.Diagnostics.Process p in ps)

{

//MessageBox.Show(p.ProcessName);

				if(p.ProcessName.ToLower()=="customerapplication")

{

p.Kill();

break;

}

}

XmlDocument doc = new XmlDocument();

doc.Load(Application.StartupPath + @"\update.xml");

XmlElement root = doc.DocumentElement;

XmlNode updateNode = root.SelectSingleNode("filelist");

string path = updateNode.Attributes["sourcepath"].Value;

int count = int.Parse(updateNode.Attributes["count"].Value);

for(int i=0;i<count;i++)

{

XmlNode itemNode = updateNode.ChildNodes[i];

string fileName = itemNode.Attributes["name"].Value;

FileInfo fi = new FileInfo(fileName);

fi.Delete();

//File.Delete(Application.StartupPath + @"\" + fileName);

				this.label1.Text = "    : " + fileName + " (" + itemNode.Attributes["size"].Value + ") ...";

FileStream fs = File.Open(fileName,FileMode.Create,FileAccess.Write);

fs.Write(System.Convert.FromBase64String(itemNode.SelectSingleNode("value").InnerText),0,int.Parse(itemNode.Attributes["size"].Value));

fs.Close();

}

label1.Text = "    ";

File.Delete(Application.StartupPath + @"\update.xml");

label1.Text = "          ...";

System.Diagnostics.Process.Start("CustomerApplication.exe");

Close();

Application.Exit();

}
 
         ,         ,      ,  Process.Kill()      。      
XmlDocument Load update.xml 。 xml ,
。 , 。 。
 、  :
         ,WebService        ,        。     WebService     
, 。 ,.Net , 。 ,
《 》 : http://forums.coder.cn/ , 。


좋은 웹페이지 즐겨찾기