Issue Downloading Complete Webpage Programmatically - c#

I've been having an issue with downloading webpages automatically with WebClient. Here are the steps my code runs through:
Retrieve HTML as string
Iterate through string, retrieving valid content urls (.js, .css, .png, etc.)
Download the content
Replace urls in HTML string with the content's local file path.
Save new HTML string to "main.html".
Everything is downloaded just fine. When I try to open up the html file in Chrome, it's a blank loading screen (varies from 10 seconds to 30 seconds). When the page finally loads, it looks like basic text and broken content.
The errors in the Chrome's Developer Tools suggest a lot of the .js and .css files aren't there, even though I've verified most of them are in the specified directory.
I have tried multiple sites, each with the same result.
Here is the code to retrieve the html data:
public string ScanPage(string url)
{
Console.WriteLine("Scanning url [" + url + "].");
WebClient client = new WebClient();
client.Headers.Add("user-agent", userAgent);
client.Headers.Add(HttpRequestHeader.ContentType, "text/html");
string page = string.Empty;
try
{
page = client.DownloadString(url);
Console.WriteLine("Webpage has been scanned.");
}
catch (Exception e)
{
Console.WriteLine("Error scanning page: " + e.Message);
}
client.Dispose();
return page;
}
Begin downloading data. This method is called first.
public void DownloadPageContent(string url, string contentDirectory, params string[] customExtensions)
{
//PathSafeURL(url) takes the url and removes unsafe characters
contentDirectory += PathSafeURL(url);
if (Directory.Exists(contentDirectory))
Directory.Delete(contentDirectory, true);
if (!Directory.Exists(contentDirectory))
Directory.CreateDirectory(contentDirectory);
Uri uri = new Uri(url);
string host = uri.Host;
//PageResponse is used to check for valid URLs. Irrelevant to the issue.
PageResponse urlResponse = CheckHttpPageResponse(url);
if (urlResponse.IsSuccessful())
{
//Get the html page as a string.
string data = ScanPage(url);
if (!string.IsNullOrEmpty(data))
{
//Download files with ".js" extension.
DownloadByExtension(ref data, ".js", contentDirectory + "/", "scripts/", host);
//Same as above, but with .css files.
DownloadByExtension(ref data, ".css", contentDirectory + "/", "css/", host);
//Iterate through custom extensions (.png, .jpg, .webm, etc.)
for (int i = 0; i < customExtensions.Length; i++)
DownloadByExtension(ref data, customExtensions[i], contentDirectory + "/", "resources/", host);
string documentDirectory = contentDirectory + "/main.html";
File.Create(documentDirectory).Dispose();
File.AppendAllText(documentDirectory, data);
Console.WriteLine("Page download has completed.");
}
else
Console.WriteLine("Error retrieving page data. Data was empty.");
}
else
Console.WriteLine("Page could not be loaded. " + urlResponse.ToString());
}
public void DownloadByExtension(ref string data, string extension, string contentDirectory, string subDirectory, string host)
{
List<HtmlContent> content = new List<HtmlContent>();
IterateContentLinks(data, extension, ref content, host);
CreateContent(contentDirectory, subDirectory, content);
for (int i = 0; i < content.Count; i++)
data = data.Replace(content[i].OriginalText + content[i].Extension, content[i].LocalLink);
Console.WriteLine("Downloaded " + content.Count + " " + extension + " files.");
Console.WriteLine();
}
private void IterateContentLinks(string data, string extension, ref List<HtmlContent> content, string host)
{
int totalCount = data.TotalCharacters(extension + "\"");
for (int i = 1; i < totalCount + 1; i++)
{
int extensionIndex = data.IndexOfNth(extension + "\"", i);
int backTrackIndex = extensionIndex - 1;
//Backtrack index from the extension index until you reach the first quotation mark.
while (data[backTrackIndex] != '"')
{
backTrackIndex -= 1;
}
string text = data.Substring(backTrackIndex + 1, (extensionIndex - backTrackIndex) - 1);
string link = text;
if (link.StartsWith("//"))
link = link.Insert(0, "http:");
if (link.StartsWith("/"))
link = link.Insert(0, "http://" + host);
if (!link.Contains("/")) //Assume it's in a "test.jpg" format.
link = link.Insert(0, "http://" + host + "/");
content.Add(new HtmlContent(text, link, extension));
}
//Remove repeating links
for (int i = 0; i < content.Count; i++)
{
for (int j = i + 1; j < content.Count; j++)
{
if (content[i].OriginalText == content[j].OriginalText)
content.Remove(content[i]);
}
}
}
private void CreateContent(string contentDirectory, string subDirectory, List<HtmlContent> content)
{
if (!Directory.Exists(contentDirectory + subDirectory))
Directory.CreateDirectory(contentDirectory + subDirectory);
Random random = new Random(Guid.NewGuid().GetHashCode());
for (int i = 0; i < content.Count; i++)
{
content[i].RandomName = Extensions.RandomSymbols(random, 20, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
content[i].LocalLink = contentDirectory + subDirectory + content[i].RandomName + content[i].Extension;
bool isSuccessful = false;
DownloadFile(content[i].DownloadLink + content[i].Extension, content[i].LocalLink, ref isSuccessful);
if (isSuccessful == false)
content.Remove(content[i]);
}
}
private void DownloadFile(string url, string filePath, ref bool isSuccessful)
{
using (WebClient client = new WebClient())
{
client.Headers.Add("user-agent", userAgent);
//client.Headers.Add(HttpRequestHeader.ContentType, "image/jpg");
try
{
client.DownloadFile(url, filePath);
isSuccessful = true;
}
catch
{
isSuccessful = false;
Console.WriteLine("File [" + url + "] could not be downloaded.");
}
}
}
HTMLContent class:
public class HtmlContent
{
public string OriginalText { get; private set; }
public string DownloadLink { get; private set; }
public string Extension { get; private set; }
public string LocalLink { get; set; }
public string RandomName { get; set; }
public HtmlContent(string OriginalText, string DownloadLink, string Extension)
{
this.OriginalText = OriginalText;
this.DownloadLink = DownloadLink;
this.Extension = Extension;
}
}
As a file downloader, this works good. For HTML downloading, it's good too. But as a complete offline webpage downloader, it does not.
EDIT:
Not sure if it matter, but I forgot to show what the userAgent variable looks like:
private const string userAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36";

Related

C# Sending File to VM Directory using VMware SDK InitiateFileTransferToGuest Protocol Error --> ResponseStream Error 22 <The File Name is not valid>

I am trying to send a file to a VM on a ESXi Server from an outside Client.
I am using the VMware SDK VMWare.Vim.dll.
When i try to use the URL given by the FileTransfer Request it Fails.
Code:
public static string ServerIP
{
get { return ConfigurationManager.AppSettings["ServerIP"].ToString(); }
}
private string ServiceUrl = "https://" + ServerIP + "/sdk";
private string UserName = "ESXIUser";
ServiceContent sc = new ServiceContent();
VimClient client = new VimClientImpl();
public VmOps()
{
}
public void Connect(string password)
{
// connect to vSphere web service
sc = client.Connect(ServiceUrl);
// Login using username/password credentials
client.Login(UserName, password);
}
public void copyDatastoreFile(/*string VMName, string Folder, string sourceFilePath*/)
{
string hostpass = "ESXIUserPAssword";
string VMName = "VMname";
string Folder = "Test";
string FileName = "test.zip";
//File destination info
string BasePath = "D:";
String targetDir = BasePath + "/" + Folder;
string srcPath = BasePath + "/" + Folder + "/" + FileName;
//Connect to the ESXi
Connect(hostpass);
NameValueCollection nvcFilter = new NameValueCollection();
nvcFilter.Add("Name", VMName);
var vm = (VirtualMachine)client.FindEntityView(typeof(VirtualMachine), null, nvcFilter, null);
GuestOperationsManager gom = new GuestOperationsManager(client, sc.GuestOperationsManager);
gom.UpdateViewData();
if (gom.FileManager == null)
{
return;
}
GuestFileManager gfm = new GuestFileManager(client, gom.FileManager);
var Auth = new NamePasswordAuthentication { Password = "VMPassword", Username = "VMUSER", InteractiveSession = false };
bool exists = false;
GuestListFileInfo fInfo = gfm.ListFilesInGuest(vm.MoRef, Auth, BasePath, null,null, Folder);
exists = fInfo.Files != null;
if (!exists)
{
// Create directory where the files will be copied to
gfm.MakeDirectoryInGuest(vm.MoRef, Auth, targetDir, true);
}
// Copy Virtual Machine file To
string URL = gfm.InitiateFileTransferToGuest(vm.MoRef,
Auth,
targetDir + "/" + FileName,
new GuestFileAttributes(),
new FileInfo(srcPath).Length,
true);
UploadFile(srcPath, URL.Replace("*", ServerIP));
}
private void UploadFile(string from, string to)
{
using (WebClient wc = new WebClient())
{
string cookie = ((VimApi_60.VimService)client.VimService).CookieContainer.GetCookies(new Uri(((VimApi_60.VimService)client.VimService).Url))[0].ToString();
wc.Credentials = new NetworkCredential("ESXiUSER", "ESXIUserPAssword");
wc.Headers.Add(HttpRequestHeader.Cookie, cookie);
try
{
wc.UploadFile(to, "PUT", from);
}
catch (WebException wex)
{
if (wex.Response != null)
{
string pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd().ToString();
}
}
wc.Dispose();
}
}
URL Looks like:
"https://199.199.0.1:443/guestFile?id=22&token=23e2deef-7979-b1a8-75e5-413440d8c1377"
Cookie Looks like:
"vmware_soap_session="5e24eaa312s1245de2gg213456m23b4bd87c8e1ca"
WebException:
The remote Server returned an error:(500) Internal Server Error
ResponseStream:
\n 22\n The file Name is not valid
Anyone any experience on file Transfers with VMware SDK? Thank you for your help!
btw. it was a simple mistake, all slashs have to be switched with a double backslash. The VMWare sdk can handle the slash, but the webclient put can't.
example:
string targetDir = BasePath + "\\" + Folder;
string srcPath = BasePath + *"\\" + Folder + "\\" + FileName;

How to ignore protected pdf's?

I am writing on my pdf-word converter and I just received a really strange exception witch makes no sens to me.
Error:PdfiumViewer.PdfException:{"Unsupported security scheme"}
Its the first time that such a exception appears. but I have to be honest that I never tried to convert more then 3-4 files from pdf to word and right now I am doing more then 100 files.
Here is my code I am sry if its too long but I simply do not know on which line the error occurs
public static void PdfToImage()
{
try
{
Application application = null;
application = new Application();
string path = #"C:\Users\chnikos\Desktop\Test\Batch1\";
foreach (string file in Directory.EnumerateFiles(path, "*.pdf"))
{
var doc = application.Documents.Add();
using (var document = PdfiumViewer.PdfDocument.Load(file))
{
int pagecount = document.PageCount;
for (int index = 0; index < pagecount; index++)
{
var image = document.Render(index, 200, 200, true);
image.Save(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png", ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png");
}
string getFileName = file.Substring(file.LastIndexOf("\\"));
string getFileWithoutExtras = Regex.Replace(getFileName, #"\\", "");
string getFileWihtoutExtension = Regex.Replace(getFileWithoutExtras, #".pdf", "");
string fileName = #"C:\Users\chnikos\Desktop\Test\Batch1\" + getFileWihtoutExtension;
doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
foreach (Microsoft.Office.Interop.Word.InlineShape inline in doc.InlineShapes)
{
.....
}
doc.PageSetup.TopMargin = 28.29f;
doc.PageSetup.LeftMargin = 28.29f;
doc.PageSetup.RightMargin = 30.29f;
doc.PageSetup.BottomMargin = 28.29f;
application.ActiveDocument.SaveAs(fileName, WdSaveFormat.wdFormatDocument);
doc.Close();
string imagePath = #"C:\Users\chnikos\Desktop\Test\Batch1\";
Array.ForEach(Directory.GetFiles(imagePath, "*.png"), delegate(string deletePath) { File.Delete(deletePath); });
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
}
}

Video Thumbnail from http url

Is it any possible way to create a video thumbnail from random url?
I have some links with video and I want to make a thumbnail from that video and save the thumbnail image on local storage. If any possible way to do this ?
Here is the solution for youtube videos:-
public string GetThumbnailsUrl(string url)// this url is your youtube video url
{
string imgurl = "";
if (url != "")
{
if (!url.ToLower().Contains("embed/"))//if not an embed URL
{
string v = url;
if (url.Contains("?"))
{
v = v.Substring(v.LastIndexOf("v=") + 2);
if (v.Contains("&"))
v = v.Substring(0, v.LastIndexOf("&"));
}
else
{
v = v.Substring(v.LastIndexOf("v/") + 2);
}
int i = 0;
try
{
i = Convert.ToInt32(ConfigurationManager.AppSettings["ImageSize"].Trim());//ImageSize contains the size of image.... the value is like 0,1,2,3.....
}
catch { i = 0; }
imgurl = "http://img.youtube.com/vi/" + v + "/" + i + ".jpg";
}
else//For embed URL
{
string[] sep = new string[1] { "embed/" };
string[] ss = url.Split(sep, StringSplitOptions.None);
string key = ss[ss.Length - 1];
int i = 0;
try
{
i = Convert.ToInt32(ConfigurationManager.AppSettings["ImageSize"].Trim());
}
catch { i = 0; }
imgurl = "http://img.youtube.com/vi/" + key + "/" + i + ".jpg";
}
}
return imgurl;
}

Sending/Fowarding Emails with duplicate subject line using WebDav in C#

I have some code that uses the WEBDAV 'SEARCH' method to retrieve emails from an an Exchange Mailboxs 'Inbox' folder - my code takes the the innerXML of the HTTPWebRquests WEBresponse.
Using 'selectingSingleNode' on these namsspaces:
'urn:schemas:httpmail' & urn:schemas:mailheader
Alows me to extract the elements:
f:textdescription
d:fromd:subject
f:datareceived...and so on
I then create a collection of these details in a list and using the 'Subject' along with the URI use the 'PUT' method to recreate these messages in the 'draft's folder before using the 'MOVE' to send the mails (puts them in the sent items using '/##DavMailSubmissionURI##/"' statement.
The problem i have is the nature of the emails i am dealing with tend to come in with the same subject line so it gets confused with which emails have been sent/or not.
Does anyone know of a way around this, I dont know why the 'PUT' relies on the Subject line for the URI to the mail resource rather than say the HREF tag which is unique. Any ideas:
Code is below:
public class EmailReaderWebDav
{
public enum enmHTTPType
{
HTTP,
HTTPS,
}
private String strServer { get; set; } //"mail1" ------ Exchange server name
public String strPassword { get; set; } //"password" ------ Account Domain Password
public String strDomain { get; set; } //"mydocmian" ------ Domain
public String strMailBox { get; set; } //"mymailbox" ------ UserName
public String mailFolder { get; set; } //"inbox" ------ Mail Folder
private String httpProtocol { get; set; } //http:// ? or https://
private String mailboxURI { get; set; } //httpprotocol// + strserver + "/exhange/" + strmailbox
public List<MailStruct > ListOfEmailDetails { get; private set; }
private String strQuerySearch { get; set; }
public EmailReaderWebDav(String serverName, String domain, String mailBox, String password, String mailmailFolder,enmHTTPType HTTPType)
{
strServer = serverName;
strDomain = domain;
strMailBox = mailBox;
strPassword = password;
mailFolder = mailmailFolder;
httpProtocol = (HTTPType == enmHTTPType.HTTPS) ? "https://" : "http://";
mailboxURI = httpProtocol + strServer + "/exchange/" + strMailBox + "/inbox/";
}
public void forwardEmails(List<MailStruct> emailsToSend)
{
emailsToSend.ForEach(x => SendEmail(x,enmHTTPType.HTTP ));
}
public void MakeListofEmailsToForward()
{
String tmpQuery =
"<?xml version=\"1.0\"?>"
+ "<D:searchrequest xmlns:D = \"DAV:\" >"
+ "<D:sql>"
+ " SELECT "
+ "\"urn:schemas:mailheader:to\","
+ "\"urn:schemas:mailheader:from\","
+ "\"urn:schemas:mailheader:subject\","
+ "\"urn:schemas:httpmail:datereceived\","
+ "\"urn:schemas:httpmail:textdescription\""
+ " FROM \"" + mailboxURI + "\""
+ " WHERE \"DAV:ishidden\" = false AND \"DAV:isfolder\" = false"
+ "</D:sql>"
+ "</D:searchrequest>";
// Search Request to get emails from target folder.
HttpWebRequest SearchRequest = MakeWebRequest("SEARCH", "text/xml", mailboxURI);
Byte[] bytes = Encoding.UTF8.GetBytes((String)tmpQuery);
SearchRequest.ContentLength = bytes.Length;
Stream SearchRequestStream = SearchRequest.GetRequestStream();
SearchRequestStream.Write(bytes, 0, bytes.Length);
SearchRequestStream.Close();
// get the webresponse from the searchrequest.
WebResponse SearchResponse = MakeWebResponse(SearchRequest);
String EmailsInXML = extractXMLFromWebResponse(SearchResponse);
ListOfEmailDetails = extractMailPropertiesFromXMLString(EmailsInXML);
}
public void SendEmail(MailStruct mailToForward, enmHTTPType HTTPType)
{
String submissionUri = httpProtocol + strServer + "/" + "exchange" + "/" + strMailBox + "/##DavMailSubmissionURI##/";
String draftsUri = httpProtocol + strServer + "/" +"exchange" + "/" + strMailBox + "/Drafts/" + mailToForward.Subject + ".eml";
String message = "To: " + mailToForward.To + "\n"
+ "Subject: " + mailToForward.Subject + "\n"
+ "Date: " + mailToForward.Received
+ "X-Mailer: mailer" + "\n"
+ "MIME-Version: 1.0" + "\n"
+ "Content-Type: text/plain;" + "\n"
+ "Charset = \"iso-8859-1\"" + "\n"
+ "Content-Transfer-Encoding: 7bit" + "\n"
+ "\n" + mailToForward.MailBody;
// Request to put an email the drafts folder.
HttpWebRequest putRequest = MakeWebRequest("PUT", "message/rfc822",draftsUri );
Byte[] bytes = Encoding.UTF8.GetBytes((String)message);
putRequest.Headers.Add("Translate", "f");
putRequest.Timeout = 300000;
putRequest.ContentLength = bytes.Length;
Stream putRequestStream = putRequest.GetRequestStream();
putRequestStream.Write(bytes, 0, bytes.Length);
putRequestStream.Close();
// Put the message in the Drafts folder of the sender's mailbox.
HttpWebResponse putResponse = MakeWebResponse(putRequest);
putResponse.Close();
// Request to move the email from the drafts to the mail submission Uri.
HttpWebRequest moveRequest = MakeWebRequest("MOVE", "text/xml", draftsUri);
moveRequest.Headers.Add("Destination", submissionUri);
// Put the message in the mail submission folder.
HttpWebResponse moveResponse = MakeWebResponse(moveRequest);
moveResponse.Close();
}
private CredentialCache getCredentials(String URI)
{
CredentialCache tmpCreds = new CredentialCache();
tmpCreds.Add(new Uri(URI), "NTLM", new NetworkCredential(strMailBox, strPassword,strDomain ));
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
return tmpCreds;
}
private HttpWebRequest MakeWebRequest(String method,String contentType,String URI)
{
HttpWebRequest tmpWebRequest;
tmpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URI);
tmpWebRequest.Credentials = getCredentials (URI);
tmpWebRequest.Method = method;
tmpWebRequest.ContentType = contentType ;
return tmpWebRequest ;
}
private HttpWebResponse MakeWebResponse(HttpWebRequest webRequest)
{
HttpWebResponse tmpWebresponse = (HttpWebResponse)webRequest.GetResponse();
return tmpWebresponse;
}
WebResponse getMailsFromWebRequest(String strRootURI, String strQuerySearch)
{
HttpWebRequest SEARCHRequest;
WebResponse SEARCHResponse;
CredentialCache MyCredentialCache;
Byte[] bytes = null;
Stream SEARCHRequestStream = null;
try
{
MyCredentialCache = new CredentialCache();
MyCredentialCache.Add(new Uri(strRootURI ), "NTLM", new NetworkCredential(strMailBox.ToLower(), strPassword, strDomain));
SEARCHRequest = (HttpWebRequest)HttpWebRequest.Create(strRootURI );
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
SEARCHRequest.Credentials = MyCredentialCache;
SEARCHRequest.Method = "SEARCH";
SEARCHRequest.ContentType = "text/xml";
bytes = Encoding.UTF8.GetBytes((string)strQuerySearch);
SEARCHRequest.ContentLength = bytes.Length;
SEARCHRequestStream = SEARCHRequest.GetRequestStream();
SEARCHRequestStream.Write(bytes, 0, bytes.Length);
SEARCHResponse =(HttpWebResponse ) SEARCHRequest.GetResponse();
SEARCHRequestStream.Close();
SEARCHRequest.Timeout = 300000;
System.Text.Encoding enc = System.Text.Encoding.Default;
if (SEARCHResponse == null)
{
Console.WriteLine("Response returned NULL!");
}
else
{
Console.WriteLine(SEARCHResponse.ContentLength);
}
return SEARCHResponse;
}
catch (Exception ex)
{
Console.WriteLine("Problem: {0}", ex.Message);
return null;
}
}
private String extractXMLFromWebResponse(WebResponse SearchResponse)
{
String tmpStream;
using(StreamReader strmReader = new StreamReader(SearchResponse.GetResponseStream(), System.Text.Encoding.ASCII))
{
tmpStream = strmReader.ReadToEnd();
strmReader.Close();
}
return tmpStream;
}
private List<MailStruct > extractMailPropertiesFromXMLString(String strXmlStream)
{
List<MailStruct> tmpListOfMailProperties = new List<MailStruct>();
XmlDocument doc = new XmlDocument();
doc.InnerXml = strXmlStream ;
XmlNamespaceManager xmlNameSpaces = new XmlNamespaceManager(doc.NameTable);
xmlNameSpaces.AddNamespace("a", "DAV:");
xmlNameSpaces.AddNamespace("f", "urn:schemas:httpmail:");
xmlNameSpaces.AddNamespace("d", "urn:schemas:mailheader:");
XmlNodeList mailNodes = doc.SelectNodes("//a:propstat[a:status='HTTP/1.1 200 OK']/a:prop", xmlNameSpaces);
foreach (XmlElement node in mailNodes)
{
tmpListOfMailProperties.Add(new MailStruct()
{
MailBody = node.SelectSingleNode("//f:textdescription",xmlNameSpaces ).InnerText ,
from = node.SelectSingleNode ("//d:from",xmlNameSpaces ).InnerText ,
To = "dfoster#liquidcapital.com",
Subject = node.SelectSingleNode("//d:subject",xmlNameSpaces ).InnerText.ToString () ,
Received = node.SelectSingleNode ("//f:datereceived",xmlNameSpaces ).InnerText.ToString ()
}
);
}
return tmpListOfMailProperties;
}
public struct MailStruct
{
public String To { get; set; }
public String from { get; set; }
public String Subject { get; set; }
public String Received { get; set; }
public String MailBody { get; set; }
}
}
}
Using just the subject to identify email is, indeed, not a good way. If I remember it's correct, there are no automatic / obvious email id for exchange / webdav?
If you parse the subject to pick message, I would also pick more information of the email envelope - Like it size, length to create my own id. The best step should be that you create some sort of hash (check Cryptography) out of the whole message body OR i.e. first character of first xx word in the email body (heavier processing though). That will end up in same hash value everytime you call it on same email envelope. Of until the email content is leaved unchanged.
Looks like you're working with Exchange 2003. Be aware that WebDAV is no longer supported in Exchange Version 2010... and with 2007 and newer you can use a WSDL to do everything you need. All you need is an Exchange 2007 CAS to do this.
What I mentioned is a better longer term approach and has less headaches than parsing unsupported WEBDAV XML
To answer your question, there is a property that is unique per message. Use MFCMapi (on codeplex) to look for it. The property will be named "MessageURL" or something like that. Use that property in the URL for your webdav calls.

C# Webserver requested directory issue

I am trying to make a web server in C#, i need to get the requested url and then list the files and folders requested.This is good to get the first directory .
For Eg. My webserver root is c:\test when i open localhost i get the contents of test folder. Say Data is subfolder of c:\test, i can click on data from the browser and get into C:\test\data now when i click on any folder then the get request comes with %2F instead of c:\test\data\ok and so i am stuck.
Code to Recieve The Request :
sRequest = sBuffer.Substring(0, iStartPos - 1);
sRequest.Replace("\\", "/");
if ((sRequest.IndexOf(".") < 1) && (!sRequest.EndsWith("/")))
{
sRequest = sRequest + "/";
}
iStartPos = sRequest.LastIndexOf("/") + 1;
sRequestedFile = sRequest.Substring(iStartPos);
sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/") - 3);
if (sDirName == "/")
sLocalDir = sMyWebServerRoot;
else
{
//Get the Virtual Directory
// sLocalDir = GetLocalPath(sMyWebServerRoot, sDirName);
Console.WriteLine("i am here");
sDirName = sDirName.Substring(1, sDirName.Length - 2);
//sDirName = sDirName.Replace("/", "\\");
Console.WriteLine("Amit:" + sDirName);
string test1 = Path.Combine("C:\\test\\", sDirName);
sLocalDir = Path.Combine(#"C:\\test", sDirName);
}
Now to List Dir I have the following Function :
public String listdir(string sLocaldir,string sDirName)
{
string sresult = "";
StringBuilder sb = new StringBuilder();
sb.AppendLine("<html>");
sb.AppendLine("<head>");
sb.AppendLine("<title>Test</title>");
sb.AppendLine("</head>");
sb.AppendLine("<body>");
sb.AppendLine("<h1><center><u>Listing Folders Under " + sLocaldir + "</h1></u></center>");
string[] folderpaths = Directory.GetDirectories(sLocaldir);
sb.AppendLine("<font color=red><font size=5>Listing Directories<br>");
for (int i = 0; i < folderpaths.Length; i++)
{
string fpath = folderpaths[i];
string[] foldernames = fpath.Split('\\');
int j = foldernames.Length - 1;
string fname = foldernames[j];
string fullname;
if (sDirName != "/")
{
//fname= fname + "\\";
fullname = sDirName +"/"+ fname;
//fullname = fullname.Replace("\\", "/");
//fullname = Path.GetPathRoot("C:\\test");
Console.WriteLine("Get full path:" + fullname);
}
else
{
fullname = fname;
}
Console.WriteLine("Full Test:" + fullname);
//sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
HttpUtility.HtmlEncode(HttpUtility.UrlEncode(fullname )),
HttpUtility.HtmlEncode(fname)));
}
string[] filePaths = Directory.GetFiles(#"C:\test");
sb.AppendLine("<font color=red><font size=5>Listing Files<br>");
for (int i = 0; i < filePaths.Length; ++i)
{
string name = Path.GetFileName(filePaths[i]);
sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
HttpUtility.HtmlEncode(HttpUtility.UrlEncode(name)),
HttpUtility.HtmlEncode(name)));
}
sb.AppendLine("</ul>");
sb.AppendLine("</body>");
sb.AppendLine("</html>");
sresult = sb.ToString();
return sresult;
//Console.WriteLine(sresult);
}
Any help would be highly appreciated.
Thank you
%2F is safe encoding for the / symbol. You are HTMLEncoding the / symbol in your code above.
Your approach can be much simpler see:
http://www.codeproject.com/KB/IP/mywebserver.aspx

Categories