Solved

Asp.net and Exchange

Posted on 2004-08-31
11
642 Views
Last Modified: 2013-11-25
Q1) Can someone tell me if there is a way to count the number of emails in exchange based on a username from asp.net without the use of a component.

Basically a user logs on and i want to count the number of emails in exchange based on there logon credentials.

Q2) Also does anyone know of a good component for showing emails from exchange for asp.net


Regards

0
Comment
Question by:u1jd
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 2
11 Comments
 
LVL 17

Expert Comment

by:AerosSaga
ID: 11941091
still looking for number of messages, here is size of mailbox for said recipient.

C#

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Xml;

namespace ExchangeSDK.Snippets.CSharp
{
   class GettingSizeOfMailboxWebDAV
   {
      [STAThread]
      static void Main(string[] args)
      {
         // Variables.
         System.Net.HttpWebRequest Request = null;
         System.Net.WebResponse Response = null;
         System.Net.CredentialCache MyCredentialCache = null;
         string strMailboxURI = "http://Server/exchange/UserName/non_ipm_subtree/";
         string strUserName = "UserName";
         string strPassword = "!Password";
         string strDomain = "Domain";
         string strQuery ="";
         byte[] bytes = null;
         System.IO.Stream RequestStream = null;
         System.IO.Stream ResponseStream = null;
         XmlDocument ResponseXmlDoc = null;
         XmlNodeList HrefNodes = null;
         XmlNodeList SizeNodes = null;
         int iMailboxSize = 0;

         try
         {
            // Build the SQL query.
            strQuery = "<?xml version=\"1.0\"?>";
            strQuery += "<g:searchrequest xmlns:g=\"DAV:\">";
            strQuery += "<g:sql>SELECT \"http://schemas.microsoft.com/";
            strQuery += "mapi/proptag/x0e080003\" FROM SCOPE ";
            strQuery += "('DEEP TRAVERSAL OF \"" + strMailboxURI + "\"') ";
            strQuery += "WHERE \"DAV:isfolder\" = true";
            strQuery += "</g:sql>";
            strQuery += "</g:searchrequest>";

            // Create a new CredentialCache object and fill it with the network
            // credentials required to access the server.
            MyCredentialCache = new System.Net.CredentialCache();
            MyCredentialCache.Add( new System.Uri(strMailboxURI),
               "NTLM",
               new System.Net.NetworkCredential(strUserName, strPassword, strDomain)
               );

            // Create the HttpWebRequest object.
            Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strMailboxURI);

            // Add the network credentials to the request.
            Request.Credentials = MyCredentialCache;

            // Specify the method.
            Request.Method = "SEARCH";

            // Encode the body using UTF-8.
            bytes = Encoding.UTF8.GetBytes((string)strQuery);

            // Set the content header length.  This must be
            // done before writing data to the request stream.
            Request.ContentLength = bytes.Length;

            // Get a reference to the request stream.
            RequestStream = Request.GetRequestStream();

            // Write the SQL query to the request stream.
            RequestStream.Write(bytes, 0, bytes.Length);

            // Close the Stream object to release the connection
            // for further use.
            RequestStream.Close();

            // Set the Content Type header.
            Request.ContentType = "text/xml";

            // Set the Translate header.
            Request.Headers.Add("Translate", "F");

            // Send the SEARCH method request and get the
            // response from the server.
            Response = (HttpWebResponse)Request.GetResponse();

            // Get the XML response stream.
            ResponseStream = Response.GetResponseStream();

            // Create the XmlDocument object from the XML response stream.
            ResponseXmlDoc = new XmlDocument();
            ResponseXmlDoc.Load(ResponseStream);

            // Build a list of the DAV:href XML nodes, corresponding to the folders
            // in the mailbox.  The DAV: namespace is typically assgigned the a:
            // prefix in the XML response body.
            HrefNodes = ResponseXmlDoc.GetElementsByTagName("a:href");

            // Build a list of the http://schemas.microsoft.com/mapi/proptag/x0e080003
            // XML nodes returned in the search request. The
            // http://schemas.microsoft.com/mapi/proptag/ namespace is typically
            // assigned the d: prefix in the XML response body.
            SizeNodes = ResponseXmlDoc.GetElementsByTagName("d:x0e080003");

            // Loop through the list of nodes and total up the sizes of the
            // mailbox folders.
            for(int i=0; i<HrefNodes.Count; i++)
            {
               // Display the folder URI.
               Console.WriteLine("Folder: " + HrefNodes[i].InnerText);

               // Display the folder size.
               Console.WriteLine("Size: " + SizeNodes[i].InnerText + " bytes.");
               Console.WriteLine("");

               // Add the folder size to the running total.
               iMailboxSize += Convert.ToInt32(SizeNodes[i].InnerText);
            }

            // Display the total size of the mailbox.
            Console.WriteLine("Mailbox size: " + iMailboxSize + " bytes.");

            // Clean up.
            ResponseStream.Close();
            Response.Close();

         }
         catch(Exception ex)
         {
            // Catch any exceptions. Any error codes from the SEARCH
            // method request on the server will be caught here, also.
            Console.WriteLine(ex.Message);
         }
      }
   }
}

Visual Basic .NET

Option Explicit On
Option Strict On

Module Module1

Sub Main()

   ' Variables
   Dim Request As System.Net.HttpWebRequest
   Dim Response As System.Net.HttpWebResponse
   Dim MyCredentialCache As System.Net.CredentialCache
   Dim strServer As String
   Dim strPassword As String
   Dim strDomain As String
   Dim strUserName As String
   Dim strMailboxURI As String
   Dim strQuery As String
   Dim bytes() As Byte
   Dim RequestStream As System.IO.Stream
   Dim ResponseStream As System.IO.Stream
   Dim ResponseXmlDoc As System.Xml.XmlDocument
   Dim HrefNodes As System.Xml.XmlNodeList
   Dim SizeNodes As System.Xml.XmlNodeList
   Dim iMailboxSize As Integer

   Try
      ' Initialize variables.
      strMailboxURI = "http://server/exchange/UserName/non_ipm_subtree/"
      strUserName = "UserName"
      strPassword = "!Password"
      strDomain = "Domain"
      iMailboxSize = 0

      ' Build the SQL query.
      strQuery = "<?xml version=""1.0""?>" & _
         "<g:searchrequest xmlns:g=""DAV:"">" & _
         "<g:sql>SELECT ""http://schemas.microsoft.com/" & _
         "mapi/proptag/x0e080003"" FROM SCOPE " & _
         "('DEEP TRAVERSAL OF """ & strMailboxURI & """') " & _
         "WHERE ""DAV:isfolder"" = true" & _
         "</g:sql>" & _
         "</g:searchrequest>"


      ' Create a new CredentialCache object and fill it with the network
      ' credentials required to access the server.
      MyCredentialCache = New System.Net.CredentialCache
      MyCredentialCache.Add(New System.Uri(strMailboxURI), _
         "NTLM", _
         New System.Net.NetworkCredential(strUserName, strPassword, strDomain) _
      )

      ' Create the PUT HttpWebRequest object.
      Request = CType(System.Net.WebRequest.Create(strMailboxURI), _
      System.Net.HttpWebRequest)

      ' Add the network credentials to the request.
      Request.Credentials = MyCredentialCache

      ' Specify the SEARCH method.
      Request.Method = "SEARCH"

      ' Encode the body using UTF-8.
      bytes = System.Text.Encoding.UTF8.GetBytes(strQuery)

      ' Set the content header length.  This must be
      ' done before writing data to the request stream.
      Request.ContentLength = bytes.Length

      ' Get a reference to the request stream.
      RequestStream = Request.GetRequestStream()

      ' Write the message body to the request stream.
      RequestStream.Write(bytes, 0, bytes.Length)

      ' Close the Stream object to release the connection
      ' for further use.
      RequestStream.Close()

      ' Set the Content Type header.
      Request.ContentType = "text/xml"

      ' Set the Translate header.
      Request.Headers.Add("Translate", "F")

      ' Send the SEARCH method request and get the
      ' response from the server.
      Response = CType(Request.GetResponse(), System.Net.HttpWebResponse)

      ' Get the XML response stream.
      ResponseStream = Response.GetResponseStream()

      ' Create the XmlDocument object from the XML response stream.
      ResponseXmlDoc = New System.Xml.XmlDocument
      ResponseXmlDoc.Load(ResponseStream)

      ' Build a list of the DAV:href XML nodes, corresponding to the folders
      ' in the mailbox.  The DAV: namespace is typically assgigned the a:
      ' prefix in the XML response body.
      HrefNodes = ResponseXmlDoc.GetElementsByTagName("a:href")

      ' Build a list of the http://schemas.microsoft.com/mapi/proptag/x0e080003
      ' XML nodes returned in the search request. The
      ' http://schemas.microsoft.com/mapi/proptag/ namespace is typically
      ' assigned the d: prefix in the XML response body.
      SizeNodes = ResponseXmlDoc.GetElementsByTagName("d:x0e080003")

      ' Loop through the list of nodes and total up the sizes of the
      ' mailbox folders.
      Dim i As Integer

      For i = 0 To HrefNodes.Count - 1

         ' Display the folder URI.
         Console.WriteLine("Folder: " & HrefNodes(i).InnerText)

         ' Display the folder size.
         Console.WriteLine("Size: " & SizeNodes(i).InnerText + " bytes.")
         Console.WriteLine("")

         ' Add the folder size to the running total.
         iMailboxSize += Convert.ToInt32(SizeNodes(i).InnerText)

      Next

      ' Display the total size of the mailbox.
      Console.WriteLine("Mailbox size: " & iMailboxSize & " bytes.")

      ' Clean up.
      ResponseStream.Close()
      Response.Close()

   Catch ex As Exception

      ' Catch any exceptions. Any error codes from the
      ' SEARCH method request on the server will be caught
      ' here, also.
      Console.WriteLine(ex.Message)

   End Try

End Sub

End Module

0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 11941105
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 11941159
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

Author Comment

by:u1jd
ID: 11942134
Hey Thanks some really good code and examples. Please keep looking for a message count in C#.

Cheers
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 11942854
We can get the message count of a message queue using MSMQ Local Admin API MQMgmtGetInfo(). This API is fully supported by Microsoft on all versions of MSMQ. We can call this API from C#.NET directly as P/Invoke. Or we can write a C++ Managed wrapper over it and then call it from C#.NET. I preferred the second approach because it is much faster and there is no possibility of runtime data type mismatches as it is there in P/Invoke.
To call this API, we need two files; 1) mq.h and 2) mqrt.lib. Both these files should be there in your system if you have VC++ 7.0 (i.e., VC++ of .NET 2003) installed on your system.
Now start a new VC++ Class Library project "MsmqApiLib" in your .NET IDE.
Add mqrt.lib as an external dependency of that project. To do this, follow the steps:
1. Open the Property dialog of the Project.
2. Select "All Configurations" from the Configuration combo box.
3. Go to the "Input" under "Linker".
4. Type "mqrt.lib" in the Additional Dependencies box.
5. Click on OK. :-)

Then include the mq.h in your MsmqApiLib.cpp file -

#include <mq.h>


And then embed the following code in your function body -

//===============================================
// Machine -> Name of the remote machine
//            or NULL for local machine.
// eg, buddha
// Queue   -> Formated name of the queue
//            with "queue=" as prefix.
// eg, queue=DIRECT=OS:buddha\private$\msmqtriggersnotifications
//
// From C#.NET you can use this function as -
//
// MsmqApiLib mqLib = new MsmqApiLib();
// long count = mqLib.GetMessageCount( "buddha",
//    "queue=DIRECT=OS:buddha\private$\msmqtriggersnotifications" );
//
//=================================================
long MsmqApiLib::GetMessageCount( String *Machine, String *Queue )
{
    const wchar_t __pin* m = PtrToStringChars( Machine );
    const wchar_t __pin* q = PtrToStringChars( Queue );
    QUEUEPROPID   propId[1];
    MQPROPVARIANT propVar[1];
    HRESULT       propStatus[1];
    DWORD         cprop = 0;
    propId [cprop] = PROPID_MGMT_QUEUE_MESSAGE_COUNT;
    propVar[cprop].vt = VT_NULL;
    ++cprop;
    MQMGMTPROPS mqProps;
    mqProps.cProp    = cprop;
    mqProps.aPropID  = propId;
    mqProps.aPropVar = propVar;
    mqProps.aStatus  = propStatus;
    HRESULT hr = MQMgmtGetInfo( m, q, &mqProps );
    if( FAILED( hr ) )
    {
        return -1;
    }
    else
    {
        return mqProps.aPropVar[0].ulVal;
    }
}
//================================================


NB: Using this API you will get the message count of only ACTIVE (ie, open) queues.
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 11942870
for display:
 Change WindowHeight and WindowWidth to sizes that you like
set maxtime to the max seconds to wait
**************Begin Script*****************
WindowHeight=300
WindowWidth=300
MaxTime=5
If WScript.Arguments.Count then
     Dim ie
     Set ie=CreateObject("InternetExplorer.Application")
     ie.Navigate2 "About:Blank"
     Do While ie.Busy =True
     WScript.Sleep 10
     Loop
     ie.Height = WindowHeight
     ie.Width = WindowWidth
     ie.MenuBar =False
     ie.ToolBar =False
     ie.StatusBar =False
     ie.Document.Title="Message Window"
     ie.Resizable =False
     Set text1=ie.Document.createelement("<Div>")
     Set text2=ie.Document.createelement("<Div>")
     Dim Command
     Set Command=ie.Document.createelement("<INPUT>")
     command.type="Button"
     command.Value="Pause"
     ie.Document.body.appendchild(text1)
     ie.Document.body.appendchild(text2)
     ie.document.body.appendchild(command)
     command.onClick=GetRef("Pause")
     ie.Document.body.onKeyDown=GetRef("KeyPressed")
     text1.innerHTML=WScript.Arguments(0)
     text2.innerHTML=int(MaxTime) & " Second(s) Remain"
     Dim continue
     continue=False
     Dim Paused
     Paused=False

     ie.Visible =True
     TimeLeft=MaxTime

     Do While Continue=False And (TimeLeft Or Paused)
          If paused=False then
               Text2.innerhtml=int(TimeLeft) & " Second(s) Remain"
               TimeLeft=TimeLeft-.1
               If TimeLeft<0 Then TimeLeft=0
          End if
          WScript.Sleep 100
     Loop
     ie.Quit
     Set ie=Nothing
End if
Function KeyPressed()
Continue=True
End Function
Function Pause()
If Paused Then
     command.Value="Unpause"
     Paused = false
 Else
      command.Value="Pause"
      Paused = true
End if
End Function
**************End Script*****************
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 11942951
0
 

Author Comment

by:u1jd
ID: 11949863
I am bit lost with the managed C++ code, would this work on an intranet, basically i am a building an intranet and hosting the asp.net project on a core server with and exchange server and sql server.

The client computer would not have any api's or anything like that on.

Could you mock up a simple project showing how it works and the points are guaranteed


Thank you so much you are helping loads and saving me such a big headache
0
 
LVL 17

Accepted Solution

by:
AerosSaga earned 235 total points
ID: 11951286
Its a call to the win32api.  But you make the call in .NET so I think it should work for you you'll just have to read over the documentation.

We can get the message count of a message queue using MSMQ Local Admin API MQMgmtGetInfo(). This API is fully supported by Microsoft on all versions of MSMQ. We can call this API from C#.NET directly as P/Invoke. Or we can write a C++ Managed wrapper over it and then call it from C#.NET. I preferred the second approach because it is much faster and there is no possibility of runtime data type mismatches as it is there in P/Invoke.
To call this API, we need two files; 1) mq.h and 2) mqrt.lib. Both these files should be there in your system if you have VC++ 7.0 (i.e., VC++ of .NET 2003) installed on your system.
Now start a new VC++ Class Library project "MsmqApiLib" in your .NET IDE.
Add mqrt.lib as an external dependency of that project. To do this, follow the steps:
1. Open the Property dialog of the Project.
2. Select "All Configurations" from the Configuration combo box.
3. Go to the "Input" under "Linker".
4. Type "mqrt.lib" in the Additional Dependencies box.
5. Click on OK. :-)
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

691 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