Solved

open word doc using microsofts treeview on client computer

Posted on 2004-10-07
18
555 Views
Last Modified: 2008-01-09
##The problem##
I need to provide the user with a web page which displays a given directory struction in a treeview similar to windows explorer treeview.

The user should be able to click throw the directories and view the available sub folders and word documents.  Once the correct document has been found, the user should be able to click on the document (on the web page), and the document should open up in microsoft word on the users computer (not on the server which is hosting the document, and not open up in the users internet browser).

##What i have done so far##
the following code can map a given directory to the microsoft ie web controls treeview and allows the user to click throw the directory structure, allowing them to expand and collapse all folders and subfolders, and select a document.

The document then opens up in the WEB BROWSER (is should not open up in the web browser, instead it should open up using the users copy of microsoft word.

Please dont stop reading as I think I have a solution which you might be able to help me with!!!

##the code .net##

##webform1.aspx##
<%@ Register TagPrefix="mytree" Namespace="Microsoft.Web.UI.WebControls" Assembly="Microsoft.Web.UI.WebControls" %>
<%@ Page Language="vb" AutoEventWireup="false" debug="true" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication9.WebForm1"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>WebForm1</title>
            <meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR">
            <meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
            <meta content="JavaScript" name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
      </HEAD>
      <body>
            <form id="Form1" method="post" runat="server">
                  <asp:Label ID="lblTitle" Runat="server" text="the page title" Font-Names="Arial" Font-Bold="True" /><p>
                  <mytree:treeview id="TreeCtrl" runat="server" SystemImagesPath="TreeImages" SelectExpands="True" DefaultStyle="font-family:arial;" Target="_blank"></mytree:treeview>
            </form>
            </P>
      </body>
</HTML>

##webform1.aspx.vb##
Imports System
Imports System.IO
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports Microsoft.Web.UI.WebControls

Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents TreeCtrl As Microsoft.Web.UI.WebControls.TreeView
    Protected WithEvents lblTitle As System.Web.UI.WebControls.Label
    Protected WithEvents lblPath As System.Web.UI.WebControls.Label

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Public Sub New()
        AddHandler Page.Init, AddressOf Page_Init
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then
            '## ADDING TREE NODE "TYPE" FOR FOLDERS AND FILES
            Dim imgurl As String = "TreeImages/"
            Dim type As TreeNodeType
            type = New TreeNodeType()
            type.Type = "folder"
            type.ImageUrl = imgurl + "folder_closed.gif"
            type.ExpandedImageUrl = imgurl + "folder_opened.gif"
            TreeCtrl.TreeNodeTypes.Add(type)
            type = New TreeNodeType()
            type.Type = "file"
            type.ImageUrl = imgurl + "file.gif"
            TreeCtrl.TreeNodeTypes.Add(type)
            '## CHOOSE A LOCATION TO START GETTING THE FILES AND DIRECTORIES FROM
            GetFolders(MapPath("thedocumentsfolder"), TreeCtrl.Nodes)
        End If
    End Sub

    '## LOADS ALL THE FOLDERS AND FILES INTO THE TREE
    Public Sub GetFolders(ByVal path As String, ByVal nodes As TreeNodeCollection)
        '## ADD NODES FOR THE FOLDERS
        Dim dirs As String() = Directory.GetDirectories(path)
        Dim p As String
        Dim dp As String

        Dim files As String() = Directory.GetFiles(path, "*")
        '## ADD FOLDERS
        For Each p In dirs
            dp = p.Substring(path.Length)
            nodes.Add(Node("", p.Substring(path.Length), "folder"))
        Next
        '## ADD FILES
        For Each p In files
            nodes.Add(Node(p, p.Substring(path.Length), "file"))
        Next p
        '## ADD SUBDIRECTORIES
        Dim i As Integer
        For i = 0 To nodes.Count - 1
            If nodes(i).Type = "folder" Then
                GetFolders(dirs(i) + "\", nodes(i).Nodes)
            End If
        Next i
    End Sub

    '## CREATING THE TREE NOTES
    Private Function Node(ByVal path As String, ByVal [text] As String, ByVal type As String) As TreeNode
        Dim n As New TreeNode()
        n.Type = type
        n.Text = [text]
        If type = "file" Then
            '## REMOVING THE PHYSICAL PATH
            Dim nav As String = "/" + path.Substring(MapPath("/").Length)
            nav.Replace("\"c, "/"c)
            n.NavigateUrl = nav
            '## SETTING THE TARGET
            'n.Target = "_blank"
        End If
        Return n
    End Function

End Class

##further explanation##
as i said above this will open the document on the user computer but in the browser, it should only open up in the users copy of microsoft word

##i have a solution!##
the following code is a simple vbscript in a html file which will open a document located on the server in the users copy of microsoft word as readonly

##the code .html vbscript##
<HTML>
      <HEAD>
            <SCRIPT LANGUAGE="VBScript">
   Dim objWord
   Sub Btn1_onclick()
   call OpenDoc("http://localhost/webapplication1/thedocumentsfolder/doc1.doc")
   End Sub

   Sub OpenDoc(strLocation)

   Set objWord = CreateObject("Word.Application")
   objWord.Visible = true
   objWord.Documents.Open strLocation
   End Sub

            </SCRIPT>
            <TITLE>Launch Word</TITLE>
      </HEAD>
      <BODY>
            <INPUT TYPE="BUTTON" NAME="Btn1" VALUE="Open Word Doc">
      </BODY>
</HTML>

##i know what needs to be done but dont know how to do it :)##
I need to combine the code for the tree which is done using asp.net vb.net, with this simple vbscript code, so the asp.net part of the code uses or passes the selected document to the vbscript which will then open the document in the users copy of microsoft word, and not open it up in the users browser, and not open it up on the server which hosts the document.

##another idea!##
can hta (hypertext applications) help in anyway.  I have read that they remove all the restrictions of a web page by using a hta instead.  Any ideas?

##final thought##
it would be even better if there is a way to do this without vbvscript :)

Please help
0
Comment
Question by:narmi2
  • 9
  • 8
18 Comments
 
LVL 33

Expert Comment

by:raterus
ID: 12250924
The reason it isn't working is because you are using serverside objects to open the word document CreateObject("Word.Application").  That is for working with word documents on the server!, never on the client.

To open it up on the client, simply link to the document on the server, with a <a href="worddoc.doc">click me</a> or you can response.redirect("worddoc.doc").
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12251463
i think it is opening in browser instead of word...bcz navigateURL property is supposed to work that way...

 Dim nav As String = "/" + path.Substring(MapPath("/").Length)
            nav.Replace("\"c, "/"c)
            n.NavigateUrl = nav
            '## SETTING THE TARGET
            'n.Target = "_blank"


0
 
LVL 15

Expert Comment

by:praneetha
ID: 12251963
read the accepted answer in that post..

guess you can't open the word document in client application

so you have to do it in the IE...

0
 
LVL 1

Author Comment

by:narmi2
ID: 12252050
is it not possible to pass the selected file information to this script below.  As this script can open a file on a server on the users computer using microsoft word, and not the browser!

<HTML>
     <HEAD>
          <SCRIPT LANGUAGE="VBScript">
   Dim objWord
   Sub Btn1_onclick()
   call OpenDoc("http://servername/webapplication1/thedocumentsfolder/doc1.doc")
   End Sub

   Sub OpenDoc(strLocation)

   Set objWord = CreateObject("Word.Application")
   objWord.Visible = true
   objWord.Documents.Open strLocation
   End Sub

          </SCRIPT>
          <TITLE>Launch Word</TITLE>
     </HEAD>
     <BODY>
          <INPUT TYPE="BUTTON" NAME="Btn1" VALUE="Open Word Doc">
     </BODY>
</HTML>
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12252102
you have to set the autopostback of tree = true...

and at the selectionchangedindex event...you can write this code...

but you have to decide..whether you want autopostback=true....
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12252145
guess u can do it using vbscript...

same code..
0
 
LVL 1

Author Comment

by:narmi2
ID: 12252239
@ praneetha - if it comes down to autopostback, i will have to use it :)

@ raterus - where do i add response.redirect("worddoc.doc").  How am i supposed to use <a href="worddoc.doc">click me</a>.  I need the folder name in the "click me" bit.

thanks for the replies
0
 
LVL 1

Author Comment

by:narmi2
ID: 12252250
[quote from praneetha]guess u can do it using vbscript...

same code..[/quote]

Can you give me an example?
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12252430
ok narmi..

i have made few changes in your code...

this is C#..just change it to vb.net please...

this is in your function Node

just removed navigate url bcz when u have navigate  url as i said it opens in IE

TreeNode n=new TreeNode();
                  n.Type=type1;
                  n.Text=text1;
                  if(type1=="file")
                  {
                  string nav="/"+path.Substring(MapPath("/").Length);
                  nav=nav.Replace("\\","/");
                  n.NodeData=nav; // i am just storing the path in a nodedata attribute of a tree
                  
                  }
                  return n;


and in html part this is the javascript...but for this to work...

you have to do this...which you may not expect many client would have....

NOTE For Word Automation to succeed, you must set your browser to Enable or to Prompt for Initialize and script ActiveX controls not marked as safe . If you set your browser to Disable, then the earlier sample code may produce a runtime error and may not work as expected.
(from MSDN)

<SCRIPT event="onselectedindexchange" for="TreeView1">
testfn1(TreeView1.getTreeNode(TreeView1.selectedNodeIndex).getAttribute("NodeData"));
</SCRIPT>
            <script language=javascript>
            function testfn1(strloc)
            {
            alert(strloc);
            var xObj = new ActiveXObject("Word.Application");
            xObj.Visible=true;
            xObj.Documents.Open("http://webservername"+strloc);//change your webservername
            }
            </script>

so good luck
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:narmi2
ID: 12256815
Excellent

I tried using this code, but nothing happens, not even an error?

The html now looks like this

<body>
      <form id="Form1" method="post" runat="server">
            <asp:Label ID="lblTitle" Runat="server" text="Company Commercial Precedents Index" Font-Names="Arial" Font-Bold="True">Company Commercial Precedents Index</asp:Label>
            <P>
                  <asp:DropDownList ID="ddlExpand" Runat="server" AutoPostBack="True" />
                  <br>
                  <mytree:treeview id="TreeCtrl" runat="server" SystemImagesPath="TreeImages" SelectExpands="True" DefaultStyle="font-family:arial;" Target="_blank" AutoPostBack="True"></mytree:treeview>
            </P>
      </form>
      <script event="selectedindexchange" for="TreeCtrl">
            testfn1(TreeCtrl.getTreeNode(TreeCtrl.selectednodeindex).getAttribute("NodeData"));
      </script>
      <script language="javascript">
            function testfn1(strloc)
            {
                  alert(strloc);
                  var xObj = new ActiveXObject("Word.Application");
                  xObj.Visible = true;
                  xObj.Documents.Open("http://localhost/"+strloc);
            }
      </script>
</body>
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12259154
<script event="onselectedindexchange" for="TreeCtrl">
          testfn1(TreeCtrl.getTreeNode(TreeCtrl.selectednodeindex).getAttribute("NodeData"));
     </script>
     <script language="javascript">
          function testfn1(strloc)
          {
               alert(strloc);
               var xObj = new ActiveXObject("Word.Application");
               xObj.Visible = true;
               xObj.Documents.Open("http://localhost/"+strloc);
          }
     </script>
this one should be in between <head></head>...not in form..

and it is onselectindexchange...not just selectindexchange
0
 
LVL 1

Author Comment

by:narmi2
ID: 12259601
i get the following error

Microsoft JScript runtime error: 'TreeCtrl.GetTreeNode(...)' is null or not an object

But thanks for the help anyway!
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12259697
TreeNode n=new TreeNode();
               n.Type=type1;
               n.Text=text1;
               if(type1=="file")
               {
               string nav="/"+path.Substring(MapPath("/").Length);
               nav=nav.Replace("\\","/");
               n.NodeData=nav; // i am just storing the path in a nodedata attribute of a tree
               
               }
               return n;


did u change that in your Function caled Node()...
0
 
LVL 1

Author Comment

by:narmi2
ID: 12260202
yes i did, but nevermind, i got it working.  

Im not to sure what to do about the points as your answer made me think of another solution.

Im not trying to be stingy or anything like that.  If i click your name as the accepted answer, other people trying to get this to work will not be successful.

any advice?
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12260216
you can post what you have done..and say u got it working using that way...i would be interested in knowing too
0
 
LVL 1

Author Comment

by:narmi2
ID: 12274941
Heres the solution, but it looks like i was wrong.  It does not work unless you are using the actual server to view the page.

It gives an error message when i transfer it to the real server off from the test server

##the error##
Microsoft JScript runtime error: Automation server can't create object
##and highlights the following line##
var objWord = new ActiveXObject('Word.Application')

Imports System
Imports System.IO
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Text
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports Microsoft.Web.UI.WebControls

Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents TreeCtrl As Microsoft.Web.UI.WebControls.TreeView
    Protected WithEvents lblTitle As System.Web.UI.WebControls.Label
    Protected WithEvents ddlExpand As System.Web.UI.WebControls.DropDownList
    Protected WithEvents lblPath As System.Web.UI.WebControls.Label

    Dim nav As String

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Public Sub New()
        AddHandler Page.Init, AddressOf Page_Init
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then
            '## ADDING TREE NODE "TYPE" FOR FOLDERS AND FILES
            Dim imgurl As String = "TreeImages/"
            Dim type As TreeNodeType
            type = New TreeNodeType()
            type.Type = "folder"
            type.ImageUrl = imgurl + "folder_closed.gif"
            type.ExpandedImageUrl = imgurl + "folder_opened.gif"
            TreeCtrl.TreeNodeTypes.Add(type)
            type = New TreeNodeType()
            type.Type = "file"
            type.ImageUrl = imgurl + "file.gif"
            TreeCtrl.TreeNodeTypes.Add(type)
            '## CHOOSE A LOCATION TO START GETTING THE FILES AND DIRECTORIES FROM
            GetFolders(MapPath("TheMainFolder"), TreeCtrl.Nodes)
        End If
    End Sub

    '## LOADS ALL THE FOLDERS AND FILES INTO THE TREE
    Public Sub GetFolders(ByVal path As String, ByVal nodes As TreeNodeCollection)
        '## ADD NODES FOR THE FOLDERS
        Dim dirs As String() = Directory.GetDirectories(path)
        Dim p As String
        Dim dp As String

        Dim files As String() = Directory.GetFiles(path, "*")
        '## ADD FOLDERS
        For Each p In dirs
            dp = p.Substring(path.Length)
            nodes.Add(Node("", p.Substring(path.Length), "folder"))
        Next
        '## ADD FILES
        For Each p In files
            nodes.Add(Node(p, p.Substring(path.Length), "file"))
        Next p
        '## ADD SUBDIRECTORIES
        Dim i As Integer
        For i = 0 To nodes.Count - 1
            If nodes(i).Type = "folder" Then
                GetFolders(dirs(i) + "\", nodes(i).Nodes)
            End If
        Next i
    End Sub

    '## CREATING THE TREE NOTES
    Private Function Node(ByVal path As String, ByVal [text] As String, ByVal type As String) As TreeNode
        Dim n As New TreeNode()
        n.Type = type
        n.Text = [text]
        If type = "file" Then
            '## REMOVING THE PHYSICAL PATH
            nav = "/" + path.Substring(MapPath("/").Length)
            nav.Replace("\"c, "/"c)
            n.NodeData = nav
        End If
        Return n
    End Function

    Private Sub ddlExpand_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlExpand.SelectedIndexChanged
        TreeCtrl.ExpandLevel = ddlExpand.SelectedItem.Text
    End Sub

    Private Sub ddlExpand_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlExpand.Load
        If Not IsPostBack Then
            Dim i As Integer
            For i = 0 To 5
                ddlExpand.Items.Add(i)
            Next i
        End If
    End Sub

    Private Sub TreeCtrl_SelectedIndexChange(ByVal sender As Object, ByVal e As Microsoft.Web.UI.WebControls.TreeViewSelectEventArgs) Handles TreeCtrl.SelectedIndexChange
        Dim selectednode As TreeNode = TreeCtrl.GetNodeFromIndex(e.NewNode)
        Dim strSelectedDoc As String = "http://ServerName" & selectednode.NodeData.ToString()
        Dim strSelectedDoc2 As String = strSelectedDoc.Replace("\", "/")

        If strSelectedDoc2 <> "http://ServerName" Then
            Dim myJString As StringBuilder = New StringBuilder()
            myJString.Append("<script language='javascript'>")
            myJString.Append("var objWord = new ActiveXObject('Word.Application');")
            myJString.Append("objWord.visible = true;")
            myJString.Append("objWord.Documents.Open('" & strSelectedDoc2 & "')")
            myJString.Append("</script>")
            RegisterStartupScript("JString", myJString.ToString())
        End If
    End Sub
End Class

however this does work on the test server!
0
 
LVL 1

Author Comment

by:narmi2
ID: 12275218
got it worrking

i just enabled active x in web browser settings for local intranet!
0
 
LVL 15

Accepted Solution

by:
praneetha earned 500 total points
ID: 12276887
yeah u r right...your code works only when server and test machine is the same...

and in mine you have to enable ACTIVE X....which is not safe i guess....

but glad you got it working
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Pick image, show data 4 33
crm written in asp.net / c# 1 42
popup message 3 27
Javascript in a user control not working 17 53
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now