I am using following code to download PDF from a SOAP service. It works fine but instead of content in the PDF file, all pages are blank.
string path = Request.PhysicalApplicationPath + "request.txt";
string response = HttpSOAPRequest(GetRequestXML(path), null, "https://soap.service", "http://tempuri.org/retrieveContract");
string[] seperator = new string[] {"--MIME_Boundary"};
string[] splitRes = response.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
string xx = splitRes[1];
byte[] final = Encoding.UTF8.GetBytes(xx.Trim());
PDF with same number of page as retruned by the soap service gets created - but all pages are blank.
Please suggest, what is going wrong.
This worked for us, replace the last line by
byte[] final = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(Convert.FromBase64String(xx.Trim())));
Related
I have wriiten some code for reading textfiles from ftp server, without downloading to the local system. Now i need to display it line by line.. is it possible?
WebClient request = new WebClient();
request.Credentials = new NetworkCredential("***", "edddd");
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
ListBox1.Items.Add(fileString);
Sure! Split your file contents on new line.
var lines = fileString.Split(new string[] { "\r\n", "\n" },
StringSplitOptions.None);
Then use the array of lines returned to display as your line. Each could be an item in your list box.
I have developed a client page for wcf service. basically my page has one button and two textboxes one is for loading request xml from xml file, and another one is displaying response xml.
Problem is that after any error got from wcf service my request xml textbox ignores all xml nodes it just displays node values with even spaces.
this is working in one machine it is not working in another machine.
two machines are windows xp os, ie 7.
<TextBox ID="requesttextbox" runat="server" TextMode="MultiLine" Width="470px"
Height="300px" Wrap="false/>
button click code something like this
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.XmlResolver = null;
xmlDoc.LoadXml(requesttextbox.Text);
HttpWebRequest objHttpWebRequest = null;
HttpWebResponse objHttpWebResponse = null;
string strFinalRequestXML = xmlDoc.OuterXml;
objHttpWebRequest = (HttpWebRequest)WebRequest.Create("RequestURL");
objHttpWebRequest.Method = "POST";
objHttpWebRequest.Accept = "xml";
objHttpWebRequest.ContentType = "application/xml; charset=utf-8";
objHttpWebRequest.Timeout = 300000;
objHttpWebRequest.ContentLength = strFinalRequestXML.Length;
System.IO.StreamWriter sw = new System.IO.StreamWriter (objHttpWebRequest.GetRequestStream());
sw.Write(strFinalRequestXML);
sw.Close();
try
{
objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.GetResponse();
Stream streamResponseText = objHttpWebResponse.GetResponseStream();
StreamReader srFinalResponseText = new StreamReader(streamResponseText, Encoding.UTF8);
txtResponse.Text = string.Empty;
// formattin xml string to as xml nodes to display in textbox
System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(srFinalResponseText.ReadToEnd());
txtResponse.Text = element.ToString();
strStatusCode = objHttpWebResponse.StatusCode.GetHashCode().ToString();
}
catch (WebException objWebException)
{
}
For example:
request xml <node>test</node> <node1>test;</node1> inside request xml text box.
after error from wcf display as " test test".
i have no clue for this problem.
If you are truly using WCF, you shouldn't have to manually call the URL using HttpWebRequest and HttpWebResponse, nor should you have to parse the XML by hand. You should add the service to the Service References, see:
http://msdn.microsoft.com/en-us/library/bb628652.aspx
If it is not WCF, but instead a regular SOAP web service, you can still add it as a Web Reference, see:
http://msdn.microsoft.com/en-us/library/bb628649.aspx
Then you can write code that is a little easier:
using (var client = new MyService.MyServiceClient())
{
string foo;
foo = client.MyMethod();
}
As for the text display, there is nothing in your catch handler, so I'm not sure where the textbox would be getting any sort of value. You must be setting it somewhere outside the code snippet you have provided.
I want to be able to store a template word document in Sharepoint, and use it as a base for spitting out a word doc containing data injected into the template.
I can get the text of my word doc using code as follows:
SPSite sc = SPContext.Current.Site;
SPWeb web = sc.AllWebs["MySite"];
string contents = web.GetFileAsString("Documents/MyTemplateWord.doc");
web.Dispose();
Then I can string replace on the "contents" variable. This works fine.
I now want to "open" this new content as a word doc.
My code for this is as follows:
string attachment = "attachment; filename=MyWord.doc";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/ms-word";
HttpContext.Current.Response.Write(outputText);
HttpContext.Current.Response.End();
I'm getting an error though, and not sure how to resolve it.
Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details: Error parsing near 'ࡱ>
Now clearly it has issues parsing the "string" content.
What am I doing wrong? Is there a different way I should be doing this?
You are not reading a string, you are converting binary data to a string.
(Rembember that a docx is a zip file containing xml data).
The nature of your approach to replacing the text is flawed in this regard.
If it were not for the desire to find/replace the text, I would recommend
using(SPWeb web = new SPSite("<Site URL>").OpenWeb())
{
SPFile file = web.GetFile("<URL for the file>");
byte[] content = file.OpenBinary();
HttpContext.Current.Response.Write(content);
}
http://support.microsoft.com/kb/929265
Using a BinaryWrite to get the data to your page.
However, because you are using Word, I would recommend loading the document into an instance of the Microsoft.Office.Interop.Word objects.
However, using Word interop can be a bit of a time vampire.
1- add docx assembly to your shaepoint package https://docx.codeplex.com
2- using Novacode;
3- note the following sample download button
protected void ButtonExportToWord_Click(object sender, EventArgs e)
{
byte[] bytesInStream;
using (Stream tplStream =
SPContext.Current.Web.GetFile("/sitename/SiteAssets/word_TEMPLATE.docx").OpenBinaryStream())
{
using (MemoryStream ms = new MemoryStream((int)tplStream.Length))
{
CopyStream(tplStream, ms);
ms.Position = 0L;
DocX doc = DocX.Load(ms);
ReplaceTextProxy(doc,"#INC#", "11111111");
doc.InsertParagraph("This is my test paragraph");
doc.Save();
bytesInStream = ms.ToArray();
}
}
Page.Response.Clear();
Page.Response.AddHeader("Content-Disposition", "attachment; filename=" +
CurrentFormId + ".docx");
Page.Response.AddHeader("Content-Length", bytesInStream.ToString());
Page.Response.ContentType = "Application/msword";
Page.Response.BinaryWrite(bytesInStream);
Page.Response.Flush();
Page.Response.Close();
//Page.Response.End();// it throws an error
}
private void ReplaceTextProxy(DocX doc, string oldvalue, string newValue)
{
doc.ReplaceText(oldvalue,newValue,false, RegexOptions.None, null, null,
MatchFormattingOptions.SubsetMatch);
}
i am using asp.net 2.0 in my project using file upload control , so browse the drive and select the file like path(D:\user doc new 2011\Montana\MT_SUTA_2010-2011.html)
but in my code seeing error is could not find the file path is
(D:\Paymycheck\OnlineTaxUserDocumentation-1\TaxesDocument\MT_SUTA_2010-2011.html) actually it is application path and take the filename only my code is
if (FileUpload.HasFile)
{
string filepath = Server.MapPath(FileUpload.FileName);
string strHTML = File.ReadAllText(filepath);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] file1 = encoding.GetBytes(strHTML);
int len = file1.Length;
byte[] file = new byte[len];
docs.TaxAuthorityName = ddlTaxAuthority.SelectedItem.Text;
docs.TaxTypeID = ddlTaxType.SelectedValue;
docs.TaxTypeDesc = ddlTaxType.SelectedItem.Text;
docs.EffectiveDate = Convert.ToDateTime(txtEffectiveDate.Text);
docs.FileName = f1;
if (ddlTaxAuthority.SelectedValue == "FD")
{
docs.Add(strHTML, file1);
}
}
error occoured in this line
string strHTML = File.ReadAllText(filepath);
i can try like this also
string FolderToSearch = System.IO.Directory.GetParent(FileUpload.PostedFile.FileName).ToString();
string f = Path.GetDirectoryName(FileUpload.PostedFile.FileName);
string f1 = FileUpload.FileName;
string filepath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string strFilePath = FileUpload.PostedFile.FileName;
string file1234 = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string filepath = FileUpload.PostedFile.FileName;
so how to get the total path drive to file
pls help me any one
thank u
hemanth
Because your are using Server.MapPath, which according to MSDN "maps the specified relative or virtual path to the corresponding physical directory on the server." You have to first call FileUpload.SaveAs method to save file on server then try to read it's content.
If you want the total client side drive path like D:\user doc new 2011\Montana\MT_SUTA_2010-2011.html for the file MT_SUTA_2010-2011.html to be uploaded via fileupload control, then try using System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName).
This will surely return the client side path of the file.
Try this it will work
string filepath = System.IO.Path.GetFullPath(fuldExcel.PostedFile.FileName);
fuldExcel.SaveAs(filepath); //fuldExcel---is my fileupload control ID
I have a C# program that is looping through all of the forms (browser enabled) in my forms library and injecting an XML node into each of them (for a newly promoted field). For some reason, when the XML is saved back to the form, the first few tags are being stripped off. Specifically, these tags are:
<?xml version="1.0"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:Contractor-DB-Form:-myXSD-2009-09-10T18-19-55" solutionVersion="1.0.1.1100" productVersion="12.0.0.0" PIVersion="1.0.0.0" href="http://echouat.rbs.us/npe/FormServerTemplates/Contractor_DB_Form.xsn"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<?mso-infoPath-file-attachment-present?>"
My code to update the XML is as follows:
private static SPListItem InsertXmlNode(SPListItem infoPathForm, string nodeToUpdateStr, string nodeToInsertStr,
string nodeInnerXmlStr, string firstNode)
{
//load form into xml document
byte[] fileBytes = infoPathForm.File.OpenBinary();
MemoryStream itemStream = new MemoryStream(fileBytes);
//Stream itemStream = infoPathForm.File.OpenBinary();
XmlDocument xmlDoc = new XmlDocument();
XmlNamespaceManager xmlNameSpaceMgr = new XmlNamespaceManager(xmlDoc.NameTable);
xmlNameSpaceMgr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-10T18:19:55");
xmlDoc.Load(itemStream);
itemStream.Close();
//inject xml
XmlNode nodeToUpdate = xmlDoc.SelectSingleNode(firstNode + nodeToUpdateStr, xmlNameSpaceMgr);
//only insert if doesn't already exist
if (xmlDoc.SelectSingleNode(firstNode + nodeToUpdateStr + "/" + nodeToInsertStr, xmlNameSpaceMgr) == null)
{
updateCounter++;
XmlNode nodeToInsert = xmlDoc.CreateNode(XmlNodeType.Element, nodeToInsertStr, "http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-10T18:19:55");
nodeToInsert.InnerText = nodeInnerXmlStr;
nodeToUpdate.AppendChild(nodeToInsert);
//get binary data for updated xml
byte[] newXmlData = Encoding.UTF8.GetBytes(xmlDoc.DocumentElement.OuterXml);
MemoryStream newMemStream = new MemoryStream(newXmlData);
//write updated binary data to the form
infoPathForm.File.SaveBinary(newMemStream);
newMemStream.Close();
infoPathForm.File.Update();
}
return infoPathForm;
}
The addition of the new node is working properly; I can see that the new XML is properly formed. It's just that the tags get stripped off once the file is loaded from the MemoryStream into the XmlDocument object. And once these tags are missing, the forms won't open anymore in IP.
PLEASE HELP!
Thank you!
Change the line which reads:
byte[] newXmlData = Encoding.UTF8.GetBytes(xmlDoc.DocumentElement.OuterXml);
to read:
byte[] newXmlData = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);