Link to home
Start Free TrialLog in
Avatar of narmi2
narmi2

asked on

open word doc using microsofts treeview on client computer

##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
Avatar of raterus
raterus
Flag of United States of America image

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").
Avatar of praneetha
praneetha

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"


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...

Avatar of narmi2

ASKER

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>
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....
guess u can do it using vbscript...

same code..
Avatar of narmi2

ASKER

@ 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
Avatar of narmi2

ASKER

[quote from praneetha]guess u can do it using vbscript...

same code..[/quote]

Can you give me an example?
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
Avatar of narmi2

ASKER

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>
<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
Avatar of narmi2

ASKER

i get the following error

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

But thanks for the help anyway!
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()...
Avatar of narmi2

ASKER

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?
you can post what you have done..and say u got it working using that way...i would be interested in knowing too
Avatar of narmi2

ASKER

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!
Avatar of narmi2

ASKER

got it worrking

i just enabled active x in web browser settings for local intranet!
ASKER CERTIFIED SOLUTION
Avatar of praneetha
praneetha

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial