Exception on downloading pdf from envelope - docusignapi

When i run this code.The Content is not allowed in prolog is coming.What is wroung in my code.
Here is code.
import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
public class GetEnvelopeDoc
{
// Enter your info:
static String username = "*****";
static String password = "*****";
static String integratorKey = "******";
static String envelopeId = "**************";
static String envelopeUri = "/envelopes/" + envelopeId;
public static void main(String[] args) throws Exception
{
String url = "https://demo.docusign.net/restapi/v2/login_information";
String baseURL = ""; // we will retrieve this
String accountId = ""; // will retrieve
String authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + username + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
//
// STEP 1 - Login
//
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
int statusValue = conn.getResponseCode(); // side-effect of this call is to fire the request off
if( statusValue != 200 ) // 200 = OK
{
System.out.print("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// we use xPath to get the baseUrl and accountId from the XML response body
BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream() ));
StringBuilder responseText = new StringBuilder(); String line = null;
while ( (line = br.readLine()) != null)
responseText.append(line);
String token1 = "//*[1]/*[local-name()='baseUrl']";
String token2 = "//*[1]/*[local-name()='accountId']";
XPath xPath = XPathFactory.newInstance().newXPath();
baseURL = xPath.evaluate(token1, new InputSource(new StringReader(responseText.toString())));
accountId = xPath.evaluate(token2, new InputSource(new StringReader(responseText.toString())));
//--- display results
System.out.println("baseUrl = " + baseURL + "\naccountId = " + accountId);
//
// STEP 2 - Get Info on Envelope's Document(s)
//
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Read the response
InputStreamReader isr = new InputStreamReader(new DataInputStream( conn.getInputStream() ));
System.out.println(isr.toString());
br = new BufferedReader(isr);
StringBuilder response = new StringBuilder();
while ( (line = br.readLine()) != null)
response.append(line);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//*[1]/*[local-name()='envelopeDocument']");
Object result = expr.evaluate(new InputSource(new StringReader(response.toString())), XPathConstants.NODESET);
//--- display results
System.out.println("\nDocument List -->");
int cnt = -1;
NodeList documents = (NodeList) result;
String[] docURIs = new String[documents.getLength()];
for (int i = 0; i < documents.getLength(); i++)
{
Node node = documents.item( i );
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
NodeList docNodes = node.getChildNodes();
for (int j = 0; j < docNodes.getLength(); j++)
{
if( docNodes.item(j).getLocalName().equals("documentId"))
System.out.print("documentId: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("name"))
System.out.print(", name: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("uri"))
{
docURIs[++cnt] = docNodes.item(j).getTextContent(); // store the uris for later
System.out.print(", uri: " + docURIs[cnt]);
}
}
System.out.println();
}
}
//
// STEP 3 - Download the document(s)
//
for( int i = 0; i < docURIs.length; i++)
{
// append document uri to url for each document
conn = (HttpURLConnection)new URL(baseURL + docURIs[i]).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
statusValue = conn.getResponseCode();
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Grab the document data and write to a local file
isr = new InputStreamReader( conn.getInputStream() );
br = new BufferedReader(isr);
StringBuilder response2 = new StringBuilder();
while ( (line = br.readLine()) != null)
response2.append(line);
BufferedWriter out = new BufferedWriter(new FileWriter("document_" + i + ".pdf"));
out.write(response2.toString());
out.close();
}
System.out.println("\nDone downloading document(s)!");
}
}

Your question is not very clear, I don't know what you mean when you say "the content is not allowed in prolog", however it looks like you have some extra characters in your code. Was this part a copy-paste error? You have the > symbols in front of each of these lines.
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request

Related

Populating Custom merge fields into Docusign template using Embedded Signing

In Salesforce Community, we are using Embedded Signing using Docusign Connect for the clients to sign the documents. We are having issue in populating the merge fields in the template. We are trying to use DocuSignAPI.CustomField and DocuSignAPI.ArrayOfCustomField but unable to do so. Could someone please look into the code and help us identify the issue? Thank you!
/*=====================================================================
SendToDocuSignController
=====================================================================*/
public without sharing class SendToDocuSignController {
private final list<Contact> lstcontact ;
private final Application__c objApplication;
private final list<DocuSign_Lease_Mapping__c> lstDocuSignLeaseMapping;
private final list<AddOns__c> lstAddOns;
Private static string trace_value = 'SFDC_002_SOAP_sender_view'; // Used for tracing API calls
Private static string trace_key = 'X-ray';
// Demo code
Public string sender_view_url {get;set;}
Public string sender_return_url {get;set;} // Required. Where DS redirects to after sending
Public string signer_email {get;set;} // Required
Public string signer_name {get;set;} // Required
Public string email_message {get;set;} // Optional
Public string output {get;set;}
Public string error_code {get;set;} // Null means no error
Public string error_message {get;set;}
// Demo code
public String envelopeId {get;set;}
private Constants__c objConstantSetting = Constants__c.getOrgDefaults();
private String accountId = 'd66c97b3-f210-41c5-8dcc-1c617d4431d8'; //'3753234'
private String userId = objConstantSetting.Docusign_User_ID__c;
private String password = objConstantSetting.Docusign_Password__c;
private String integratorsKey = objConstantSetting.Docusign_Integrator_Key__c;
private String webServiceUrl = objConstantSetting.Docusign_webServiceUrl__c;
public SendToDocuSignController()
{
System.debug('lstcontact');
String ApplicationID = 'a070t000000EF9Y'; //a070t000000MBpi
this.lstAddOns = [SELECT Id ,Name ,Application__c FROM AddOns__c where Application__c =:ApplicationID ];
this.objApplication = [select Id, Household__c, Property__c from Application__c where id = :ApplicationID ];
this.lstcontact = [select Id, Name, RecordType.Name , Email from Contact where RecordType.Name != 'Minor Child' AND Email != null AND AccountId =:objApplication.Household__c ];
System.debug('lstcontact'+lstcontact);
if(lstAddOns.isEmpty())
this.lstDocuSignLeaseMapping = [select DocuSign_Template_ID__c, Name, Property__c from DocuSign_Lease_Mapping__c where Property__c =: objApplication.Property__c ];
else
this.lstDocuSignLeaseMapping = [select DocuSign_Template_ID__c, Name, Property__c from DocuSign_Lease_Mapping__c where Property__c =: objApplication.Property__c AND Concession_Addendum__c = false];
envelopeId = 'Not sent yet';
}
/*****************************************************************
Method Name : SendNow()
Purpose: Creates Docusign envelope and sends an email from docusign to sign the docs
******************************************************************/
public PageReference SendNow()
{
DocuSignAPI.APIServiceSoap dsApiSend = new DocuSignAPI.APIServiceSoap();
dsApiSend.endpoint_x = webServiceUrl;
//Set Authentication
String auth = '<DocuSignCredentials><Username>'+ userId
+'</Username><Password>' + password
+ '</Password><IntegratorKey>' + integratorsKey
+ '</IntegratorKey></DocuSignCredentials>';
System.debug('Setting authentication to: ' + auth);
dsApiSend.inputHttpHeaders_x = new Map<String, String>();
dsApiSend.inputHttpHeaders_x.put('X-DocuSign-Authentication', auth);
dsApiSend.inputHttpHeaders_x.put(trace_key, trace_value);
//Create Docusign envelope information object
DocuSignAPI.EnvelopeInformation EnvelopeInformation = new DocuSignAPI.EnvelopeInformation ();
EnvelopeInformation.Subject = Label.Docusign_Email_Subject ;
EnvelopeInformation.EmailBlurb = ' ';
EnvelopeInformation.AccountId = objConstantSetting.Docusign_Account_ID__c;
System.debug('EnvelopeInformation'+EnvelopeInformation);
DocuSignAPI.CustomField field = new DocuSignAPI.CustomField ();
field.Name = 'DSFSSourceObjectId'; //'dsfs__Application__c';
field.Value = 'a070t000000EF9Y'; //'01I0t0000000FK3';
field.Show = 'true';
field.CustomFieldType = 'Text';
DocuSignAPI.ArrayOfCustomField arrayOfCustomField = new DocuSignAPI.ArrayOfCustomField();
arrayOfCustomField.CustomField = new DocuSignAPI.CustomField[1];
arrayOfCustomField.CustomField[0] = field;
EnvelopeInformation.CustomFields = arrayOfCustomField;
System.debug('PB: field.Name & field.value = '+ field.Name +field.value);
//Create Docusign TemplateReference object
DocusignAPI.TemplateReference reference = new DocusignAPI.TemplateReference();
DocuSignAPI.ArrayOfTemplateReference templateReferenceArray = new DocuSignAPI.ArrayOfTemplateReference();
templateReferenceArray.TemplateReference = new DocuSignAPI.TemplateReference[lstDocuSignLeaseMapping.size()];
System.debug('lst of template'+lstDocuSignLeaseMapping);
System.debug('lst of lstDocuSignLeaseMapping.size()'+lstDocuSignLeaseMapping.size());
Integer seq =0;
Integer index = 0;
Integer signerNumber = 1;
//Create Docusign recipient object
DocuSignAPI.Recipient recipient = new DocuSignAPI.Recipient();
DocuSignAPI.ArrayOfRecipient1 Recipients = new DocuSignAPI.ArrayOfRecipient1();
Recipients.Recipient = new DocuSignAPI.Recipient[lstcontact.size()];
DocuSignAPI.TemplateReferenceRoleAssignment roleAssignment1;
DocuSignAPI.TemplateReferenceRoleAssignment roleAssignment2;
for(Contact objcontact : lstcontact) {
recipient = new DocuSignAPI.Recipient();
recipient.ID = signerNumber;
recipient.Type_x = 'Signer';
recipient.roleName = 'Signer ' + String.valueOf(signerNumber);
recipient.RoutingOrder = signerNumber;
recipient.Email = objcontact.Email;
recipient.UserName = objcontact.Name ;
recipient.RequireIDLookup = false;
recipient.CaptiveInfo = new DocuSignAPI.RecipientCaptiveInfo();
recipient.CaptiveInfo.ClientUserId = objcontact.Id;
System.debug('recipient'+recipient);
Recipients.Recipient[seq] = recipient;
if(signerNumber == 1) {
roleAssignment1 = new DocuSignAPI.TemplateReferenceRoleAssignment();
roleAssignment1.RoleName = recipient.RoleName;
roleAssignment1.RecipientID = recipient.ID;
}
if(signerNumber == 2) {
roleAssignment2 = new DocuSignAPI.TemplateReferenceRoleAssignment();
roleAssignment2.RoleName = recipient.RoleName;
roleAssignment2.RecipientID = recipient.ID;
}
signerNumber++;
seq++;
}
seq = 1;
for(DocuSign_Lease_Mapping__c objDocuSignLeaseMapping : lstDocuSignLeaseMapping){
reference = new DocusignAPI.TemplateReference();
reference.TemplateLocation = 'Server';
reference.Template = objDocuSignLeaseMapping.DocuSign_Template_ID__c;
reference.sequence = seq;
reference.RoleAssignments = new DocuSignAPI.ArrayOfTemplateReferenceRoleAssignment();
reference.RoleAssignments.RoleAssignment = new DocuSignAPI.TemplateReferenceRoleAssignment[3];
reference.RoleAssignments.RoleAssignment[0] = roleAssignment1;
reference.RoleAssignments.RoleAssignment[1] = roleAssignment2;
templateReferenceArray.TemplateReference[index] = reference;
index++;
seq++;
}
//create and send envelope with template
try {
//DocuSignAPI.EnvelopeStatus es1 = dsApiSend.CreateAndSendEnvelope(EnvelopeInformation);
DocuSignAPI.EnvelopeStatus es
= dsApiSend.CreateEnvelopeFromTemplates(templateReferenceArray, Recipients ,EnvelopeInformation,true);
envelopeId = es.EnvelopeID;
DocuSignAPI.RequestRecipientTokenClientURLs clientURLs = new DocuSignAPI.RequestRecipientTokenClientURLs();
Blob b = Crypto.GenerateAESKey(128);
String h = EncodingUtil.ConvertTohex(b);
String guid = h.SubString(0,8)+ '-' + h.SubString(8,12) + '-' + h.SubString(12,16) + '-' + h.SubString(16,20) + '-' + h.substring(20);
DocuSignAPI.RequestRecipientTokenAuthenticationAssertion assertion = new DocuSignAPI.RequestRecipientTokenAuthenticationAssertion();
assertion.AssertionID = guid;
assertion.AuthenticationInstant = DateTime.Now();
assertion.AuthenticationMethod = 'Email';
assertion.SecurityDomain = 'force.com';
// Construct the URLs based on username
DocuSignAPI.RequestRecipientTokenClientURLs urls = new DocuSignAPI.RequestRecipientTokenClientURLs();
String urlBase = URL.getSalesforceBaseUrl().toExternalForm()+'/'+lstcontact[0].id ;
clientURLs.OnSigningComplete = urlBase + '?event=SignComplete&uname=' + recipient.UserName;
clientURLs.OnViewingComplete = urlBase + '?event=ViewComplete&uname=' + recipient.UserName;
clientURLs.OnCancel = urlBase + '?event=Cancel&uname=' + recipient.UserName;
clientURLs.OnDecline = urlBase + '?event=Decline&uname=' + recipient.UserName;
clientURLs.OnSessionTimeout = urlBase + '?event=Timeout&uname=' + recipient.UserName;
clientURLs.OnTTLExpired = urlBase + '?event=TTLExpired&uname=' + recipient.UserName;
clientURLs.OnIdCheckFailed = urlBase + '?event=IDCheck&uname=' + recipient.UserName;
clientURLs.OnAccessCodeFailed = urlBase + '?event=AccessCode&uname=' + recipient.UserName;
clientURLs.OnException = urlBase + '?event=Exception&uname=' + recipient.UserName;
// assumes apiService = preconfigured api proxy
String token;
try {
token = dsApiSend.RequestRecipientToken(envelopeId,Recipients.Recipient[0].captiveinfo.ClientUserId,Recipients.Recipient[0].UserName,Recipients.Recipient[0].Email,assertion,clientURLs);
String token1 = dsApiSend.RequestRecipientToken(envelopeId,Recipients.Recipient[1].captiveinfo.ClientUserId,Recipients.Recipient[1].UserName,Recipients.Recipient[1].Email,assertion,clientURLs);
system.debug('????????????token1??????????' + token1);
}
catch ( CalloutException e) {
System.debug('Exception - ' + e );
envelopeId = 'Exception - ' + e;
}
PageReference retURL = new PageReference(token);
retURL.setRedirect(false);
return retURL;
}
catch ( CalloutException e) {
System.debug('Exception - ' + e );
envelopeId = 'Exception - ' + e;
return null;
}
}
private String getPopURL() {
String popURL = String.valueOf(System.URL.getSalesforceBaseUrl());
if (popURL == null) {
popURL = 'https://na3.salesforce.com/apex/';
}
System.Debug('pop page: ' + popURL + 'embedPop');
return popURL + 'embedPop';
}
}

Resumable Upload using Google Mail APIs throwing exception: "Bad Request"

I am trying to insert mail to Google Mailbox using GMail APIs.
I want to upload mails of size more than 5 mb. So that I am using Resumable upload request.
I have used POST request first to initiate a resumable upload which gives "200 OK" response.
Post Request:
String postUrl = "https://www.googleapis.com/upload/gmail/v1/users/" + "<username>" + "/messages/send?uploadType=resumable";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest.Headers["Authorization"] = "Bearer " + f_token;// AccessToken;
httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
httpRequest.Headers["X-Upload-Content-Length"] = f_bytes.Length.ToString();
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
var response = (HttpWebResponse)httpRequest.GetResponse(); // 200 OK
From that response I get location URL to upload EML.
Location: https://www.googleapis.com/upload/gmail/v1/users//messages/send?uploadType=resumable&upload_id=AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw
To upload EML file I used Location URL as PUT URL to create request.
putUrl = https://www.googleapis.com/upload/gmail/v1/users/<username>/messages/send?uploadType=resumable&upload_id=AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw";
HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest1.Method = "PUT";
httpRequest1.ContentLength = f_bytes.Length;
int EndOffset = f_bytes.Length;//5120000;5242880
httpRequest1.Headers["Content-Range"] = "bytes " + 0 + "-" + EndOffset + "/" + f_bytes.Length;
httpRequest1.ContentType = "message/rfc822";
MemoryStream stream = new MemoryStream(f_bytes);
System.IO.Stream requestStream = httpRequest1.GetRequestStream();
{
stream.CopyTo(requestStream);
requestStream.Flush();
requestStream.Close();
}
HttpWebResponse f_webResponse = (HttpWebResponse)httpRequest1.GetResponse(); //Exception
Exception :
The remote server returned an error: (400) Bad Request.
Please suggest soluion to upload eml file in a particular folder of mailbox .
I am able to send mail using resumable upload.
if (f_MailService == null)
{
bool isCreated = createMailService(ref f_MailService);
}
FileStream fs = new FileStream(#p_EMLPath, FileMode.Open,FileAccess.Read);
Create HTTPRequest for sending mail :
string postUrl = "https://www.googleapis.com/upload/gmail/v1/users/ab#edu.cloudcodes.com/messages/send?uploadType=resumable";
HttpWebRequest f_httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
f_httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
f_httpRequest.Headers["X-Upload-Content-Length"] = fs.Length.ToString();
f_httpRequest.Headers["Authorization"] = "Bearer " + f_token;
f_httpRequest.Method = "POST";
//f_httpRequest.ContentLength = 524288;
f_httpRequest.ContentType = "application/json; charset=UTF-8";//"message/rfc822";
f_httpRequest.ContentLength = fs.Length;
f_httpRequest.Timeout = 6000000;
f_httpRequest.SendChunked = true;
Get Response for first POST request :
try
{
using (Stream f_ObjHttpStream = f_httpRequest.GetRequestStream())
{
}
}
catch (Exception EX)
{
}
try
{
using (var response = (HttpWebResponse)f_httpRequest.GetResponse())
{
// data = ReadResponse(response);
UploadUrl = response.Headers["Location"].ToString();
}
}
catch (WebException exception)
{
using (var response = (HttpWebResponse)exception.Response)
{
// data = ReadResponse(response);
}
}
Read EML File & send chunk data to upload
byte[] Arrbyte = new byte[1024];
int ReadByte = 0;
while (fs.Length > ReadByte)
{
bool ac = false;
int ByteRead = 0;
byte[] Data = new byte[4194304];
byte[] LastData;
//Read block of bytes from stream into the byte array
// if (ReadByte == 0)
{
ByteRead = fs.Read(Data, 0, Data.Length);
}
//else
{
if ((ReadByte + Data.Length) > fs.Length)
{
//fs.Length - ReadByte-
LastData = new byte[fs.Length - ReadByte];
ByteRead = fs.Read(LastData, 0, LastData.Length);
CallPUTReq(fs.Length, LastData);
ac = true;
}
}
//f_MsgRawStr = Convert.ToBase64String(f_bytes).TrimEnd(padding).Replace('+', '-').Replace('/', '_');
ReadByte = ReadByte + ByteRead;
if (ac == false)
{
CallPUTReq(fs.Length, Data);
}
//long pos = fs.Seek(0, SeekOrigin.Current );
//fs.Position = ReadByte;
}
private void CallPUTReq(long p_lenth, byte[] Arrbyte)
{
try
{
String postUrl = UploadUrl; //"https://www.googleapis.com/upload/gmail/v1/users/ab#edu.cloudcodes.com/messages/send?uploadType=resumable&upload_id=AEnB2UqZNtZVwWulAOhAVoFp-pZ-vTMcIXOpt_0dH_6jJecpm2Y1MNOGkE6JoDb0kn9Dt4yuHHMZWR--dBncxWQkZctF9h6jiPSL5uJDKeYE9Ut1c7-fImc";
int EndOffset = 0;
HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest1.Method = "PUT";
httpRequest1.ContentLength = Arrbyte.Length;
if (rangeStartOffset == 0)
{
EndOffset = Arrbyte.Length - 1;
}
else
{
EndOffset = rangeStartOffset + Arrbyte.Length - 1;
if (EndOffset > p_lenth)
{
EndOffset = Convert.ToInt32(p_lenth);
httpRequest1.ContentLength = EndOffset - rangeStartOffset;
}
}//5120000;5242880
httpRequest1.Headers["Content-Range"] = "bytes " + rangeStartOffset + "-" + EndOffset + "/" + p_lenth; //"bytes */" + p_lenth; //
httpRequest1.ContentType = "message/rfc822";
httpRequest1.Timeout = 6000000;
UTF8Encoding encoding = new UTF8Encoding();
Stream stream = httpRequest1.GetRequestStream();
stream.Write(Arrbyte, 0, Arrbyte.Length);
stream.Close();
try
{
using (Stream f_ObjHttpStream = httpRequest1.GetRequestStream())
{
}
}
catch (Exception EX)
{
}
WebResponse response1 = null;
try
{
using (response1 = (HttpWebResponse)httpRequest1.GetResponse())
{
}
}
catch (Exception ex)
{
// UploadUrl = response1.Headers["Location"].ToString();
}
//4194303
rangeStartOffset = EndOffset +1;
}
catch (Exception)
{
}
}

Using Epplus to import data from an Excel file to SQL Server database table

I've tried implementing thishttps://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 on an ASP.NET MVC 5 Application.
//SEE CODE BELOW
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
if (System.IO.File.Exists(excelFile))
{
System.IO.File.Delete(excelFile);
}
else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
file.SaveAs(excelFile);//WORKS FINE
//BEGINING OF IMPORT
FileInfo eFile = new FileInfo(excelFile);
using (var excelPackage = new ExcelPackage(eFile))
{
if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
{ ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
else
{
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;
else
{
var lastRow = worksheet.Dimension.End.Row;
while (lastRow >= 1)
{
var range = worksheet.Cells[lastRow, 1, lastRow, 3];
if (range.Any(c => c.Value != null))
{ break; }
lastRow--;
}
using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
{
for (var row = 2; row <= lastRow; row++)
{
var newPerson = new personalDetails
{
identificationType = worksheet.Cells[row, 1].Value.ToString(),
idNumber = worksheet.Cells[row, 2].Value.ToString(),
idSerial = worksheet.Cells[row, 3].Value.ToString(),
fullName = worksheet.Cells[row, 4].Value.ToString(),
dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
gender = worksheet.Cells[row, 6].Value.ToString()
};
DB.personalDetails.Add(newPerson);
try { db.SaveChanges(); }
catch (Exception) { }
}
}
}
}
}//END OF IMPORT
ViewBag.Message = "Your file was successfully uploaded.";
return RedirectToAction("Index");
}
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
else
{
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
}
See Picture Error
Any help would be greatly appreciated mates.
you can do like this:
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}
Details: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/

Export xml data to Excel using OpenXML

The file is downloading an xlsx file but when i tried to open the file it is saying file is corrupted. Here is the code i'm trying to use please let me know if any changes has to be done for the following.
private void button1_Click(object sender, EventArgs e)
{
ArrayList DataNode = new ArrayList();
XmlDocument xmlobj = new XmlDocument();
ArrayList FinalXML = new ArrayList();
XslCompiledTransform xXslt = new XslCompiledTransform();
xmlobj.Load(#"D:\ExcelImport\Input.xml");
xXslt.Load(#"D:\ExcelImport\demoxsl.xslt");
XmlNodeList DN ;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0 ;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw = new StringWriter();
xXslt.Transform(xml, null, sw);
FinalXML.Add(sw);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"D:\ExcelImport\OutPut\OutPut.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""schemas.openxmlformats.org/.../main"" xmlns:r=""schemas.openxmlformats.org/.../relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook.AddNewPart<WorksheetPart>();
string sheetId = workbook.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""schemas.openxmlformats.org/.../main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
WorbookXML += "<sheet name="+ AddPartXml(sheet[j], text) + " sheetId=" + j.ToString() + " r:id=" + sheetId.ToString() + " />";
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook, WorbookXML);
doc.Close();
}
}
public string AddPartXml(OpenXmlPart part, string xml)
{
Uri uri = part.Uri;
String[] sheetNames = uri.OriginalString.Split('/');
string sheetName = sheetNames[sheetNames.Length - 1].Split('.')[0];
using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}
return sheetName;
}
Thanks in advance
Vineet Mangal
private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlobj = new XmlDocument();
xmlobj.Load(#"C:\Excel Import\\Input.xml");
XslCompiledTransform xXslt = new XslCompiledTransform();
xXslt.Load(#"C:\ExportToexcel\Data.xslt");
StringWriter sw = new StringWriter();
xXslt.Transform(xmlobj, null, sw);
richTextBox2.Text = sw.ToString();
sw.Close();
XmlDocument Xdoc = new XmlDocument();
Xdoc.LoadXml(sw.ToString());
Xdoc.Save(#"c:\temp\output.xml");
StreamReader sr = File.OpenText(#"c:\temp\output.xml");
string strSheetData = sr.ReadToEnd();
ArrayList DataNode = new ArrayList();
ArrayList FinalXML = new ArrayList();
XmlNodeList DN;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw1 = new StringWriter();
xXslt.Transform(xml, null, sw1);
FinalXML.Add(sw1);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"c:\\temp\\output.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook1 = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook1.AddNewPart<WorksheetPart>();
string sheetId = workbook1.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
**WorbookXML += "<sheet name=" + "\"sheet" + (j + 1).ToString() + "\" " + " sheetId=\"" + (j + 1).ToString() + "\" r:id=\"" + sheetId.ToString() + "\" />";
AddPartXml(sheet[j], text);**
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook1, WorbookXML);
doc.Close();
}
}
public void AddPartXml(OpenXmlPart part, string xml)
{
**using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}**
}

Convert a number in scientific notation to numeric format in Excel using a macro or VBA

MS Excel has eaten my head. It is randomly converting numbers into scientific notation format. This causes a problem when I load the file saved in tab delimited format into SQL Server. I know I can provide a format file and do lot of fancy stuff. But let's say I can't.
Is there a macro which loops over all the cells and if the number in a cell is in scientific notation format then it converts it to numeric format?
Say:
Input: spaces signify different cells.
1.00E13 egalitarian
Output after macro:
10000000000000 egalitarian
I am trying this in Excel 2007.
I wrote a simple C# program to resolve this issue. Hope it's of use.
Input:
Input directory where files reside (assuming files are in .txt format).
Output:
Output directory where converted files will be spit out.
Delimiter:
Column delimiter.
The code
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Threading;
namespace ConvertToNumber
{
class Program
{
private static string ToLongString(double input)
{
string str = input.ToString().ToUpper();
// If string representation was collapsed from scientific notation, just return it:
if (!str.Contains("E"))
return str;
var positive = true;
if (input < 0)
{
positive = false;
}
string sep = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
char decSeparator = sep.ToCharArray()[0];
string[] exponentParts = str.Split('E');
string[] decimalParts = exponentParts[0].Split(decSeparator);
// Fix missing decimal point:
if (decimalParts.Length == 1)
decimalParts = new string[] { exponentParts[0], "0" };
int exponentValue = int.Parse(exponentParts[1]);
string newNumber = decimalParts[0].Replace("-","").
Replace("+","") + decimalParts[1];
string result;
if (exponentValue > 0)
{
if(positive)
result =
newNumber +
GetZeros(exponentValue - decimalParts[1].Length);
else
result = "-"+
newNumber +
GetZeros(exponentValue - decimalParts[1].Length);
}
else // Negative exponent
{
if(positive)
result =
"0" +
decSeparator +
GetZeros(exponentValue + decimalParts[0].Replace("-", "").
Replace("+", "").Length) + newNumber;
else
result =
"-0" +
decSeparator +
GetZeros(exponentValue + decimalParts[0].Replace("-", "").
Replace("+", "").Length) + newNumber;
result = result.TrimEnd('0');
}
float temp = 0.00F;
if (float.TryParse(result, out temp))
{
return result;
}
throw new Exception();
}
private static string GetZeros(int zeroCount)
{
if (zeroCount < 0)
zeroCount = Math.Abs(zeroCount);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < zeroCount; i++) sb.Append("0");
return sb.ToString();
}
static void Main(string[] args)
{
//Get Input Directory.
Console.WriteLine(#"Enter the Input Directory");
var readLine = Console.ReadLine();
if (readLine == null)
{
Console.WriteLine(#"Enter the input path properly.");
return;
}
var pathToInputDirectory = readLine.Trim();
//Get Output Directory.
Console.WriteLine(#"Enter the Output Directory");
readLine = Console.ReadLine();
if (readLine == null)
{
Console.WriteLine(#"Enter the output path properly.");
return;
}
var pathToOutputDirectory = readLine.Trim();
//Get Delimiter.
Console.WriteLine("Enter the delimiter;");
var columnDelimiter = (char) Console.Read();
//Loop over all files in the directory.
foreach (var inputFileName in Directory.GetFiles(pathToInputDirectory))
{
var outputFileWithouthNumbersInScientificNotation = string.Empty;
Console.WriteLine("Started operation on File : " + inputFileName);
if (File.Exists(inputFileName))
{
// Read the file
using (var file = new StreamReader(inputFileName))
{
string line;
while ((line = file.ReadLine()) != null)
{
String[] columns = line.Split(columnDelimiter);
var duplicateLine = string.Empty;
int lengthOfColumns = columns.Length;
int counter = 1;
foreach (var column in columns)
{
var columnDuplicate = column;
try
{
if (Regex.IsMatch(columnDuplicate.Trim(),
#"^[+-]?[0-9]+(\.[0-9]+)?[E]([+-]?[0-9]+)$",
RegexOptions.IgnoreCase))
{
Console.WriteLine("Regular expression matched for this :" + column);
columnDuplicate = ToLongString(Double.Parse
(column,
System.Globalization.NumberStyles.Float));
Console.WriteLine("Converted this no in scientific notation " +
"" + column + " to this number " +
columnDuplicate);
}
}
catch (Exception)
{
}
duplicateLine = duplicateLine + columnDuplicate;
if (counter != lengthOfColumns)
{
duplicateLine = duplicateLine + columnDelimiter.ToString();
}
counter++;
}
duplicateLine = duplicateLine + Environment.NewLine;
outputFileWithouthNumbersInScientificNotation = outputFileWithouthNumbersInScientificNotation + duplicateLine;
}
file.Close();
}
var outputFilePathWithoutNumbersInScientificNotation
= Path.Combine(pathToOutputDirectory, Path.GetFileName(inputFileName));
//Create the directory if it does not exist.
if (!Directory.Exists(pathToOutputDirectory))
Directory.CreateDirectory(pathToOutputDirectory);
using (var outputFile =
new StreamWriter(outputFilePathWithoutNumbersInScientificNotation))
{
outputFile.Write(outputFileWithouthNumbersInScientificNotation);
outputFile.Close();
}
Console.WriteLine("The transformed file is here :" +
outputFilePathWithoutNumbersInScientificNotation);
}
}
}
}
}
This works fairly well in case of huge files which we are unable to open in MS Excel.
Thanks Peter.
I updated your original work to:
1) take in an input file or path
2) only write out a processing statement after every 1000 lines read
3) write the transformed lines to the output file as they are processed so a potentially large string is not kept hanging around
4) added a readkey at the end so that console does not exit automatically while debuggging
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Threading;
namespace ConvertScientificToLong
{
class Program
{
private static string ToLongString(double input)
{
string str = input.ToString().ToUpper();
// If string representation was collapsed from scientific notation, just return it:
if (!str.Contains("E"))
return str;
var positive = true;
if (input < 0)
{
positive = false;
}
string sep = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
char decSeparator = sep.ToCharArray()[0];
string[] exponentParts = str.Split('E');
string[] decimalParts = exponentParts[0].Split(decSeparator);
// Fix missing decimal point:
if (decimalParts.Length == 1)
decimalParts = new string[] { exponentParts[0], "0" };
int exponentValue = int.Parse(exponentParts[1]);
string newNumber = decimalParts[0].Replace("-", "").
Replace("+", "") + decimalParts[1];
string result;
if (exponentValue > 0)
{
if (positive)
result =
newNumber +
GetZeros(exponentValue - decimalParts[1].Length);
else
result = "-" +
newNumber +
GetZeros(exponentValue - decimalParts[1].Length);
}
else // Negative exponent
{
if (positive)
result =
"0" +
decSeparator +
GetZeros(exponentValue + decimalParts[0].Replace("-", "").
Replace("+", "").Length) + newNumber;
else
result =
"-0" +
decSeparator +
GetZeros(exponentValue + decimalParts[0].Replace("-", "").
Replace("+", "").Length) + newNumber;
result = result.TrimEnd('0');
}
float temp = 0.00F;
if (float.TryParse(result, out temp))
{
return result;
}
throw new Exception();
}
private static string GetZeros(int zeroCount)
{
if (zeroCount < 0)
zeroCount = Math.Abs(zeroCount);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < zeroCount; i++) sb.Append("0");
return sb.ToString();
}
static void Main(string[] args)
{
//Get Input Directory.
Console.WriteLine(#"Enter the Input Directory or File Path");
var readLine = Console.ReadLine();
if (readLine == null)
{
Console.WriteLine(#"Enter the input path properly.");
return;
}
var pathToInputDirectory = readLine.Trim();
//Get Output Directory.
Console.WriteLine(#"Enter the Output Directory");
readLine = Console.ReadLine();
if (readLine == null)
{
Console.WriteLine(#"Enter the output path properly.");
return;
}
var pathToOutputDirectory = readLine.Trim();
//Get Delimiter.
Console.WriteLine("Enter the delimiter;");
var columnDelimiter = (char)Console.Read();
string[] inputFiles = null;
if (File.Exists(pathToInputDirectory))
{
inputFiles = new String[]{pathToInputDirectory};
}
else
{
inputFiles = Directory.GetFiles(pathToInputDirectory);
}
//Loop over all files in the directory.
foreach (var inputFileName in inputFiles)
{
var outputFileWithouthNumbersInScientificNotation = string.Empty;
Console.WriteLine("Started operation on File : " + inputFileName);
if (File.Exists(inputFileName))
{
string outputFilePathWithoutNumbersInScientificNotation
= Path.Combine(pathToOutputDirectory, Path.GetFileName(inputFileName));
//Create the directory if it does not exist.
if (!Directory.Exists(pathToOutputDirectory))
Directory.CreateDirectory(pathToOutputDirectory);
using (var outputFile =
new StreamWriter(outputFilePathWithoutNumbersInScientificNotation))
{
// Read the file
using (StreamReader file = new StreamReader(inputFileName))
{
string line;
int lineCount = 0;
while ((line = file.ReadLine()) != null)
{
String[] columns = line.Split(columnDelimiter);
var duplicateLine = string.Empty;
int lengthOfColumns = columns.Length;
int counter = 1;
foreach (var column in columns)
{
var columnDuplicate = column;
try
{
if (Regex.IsMatch(columnDuplicate.Trim(),
#"^[+-]?[0-9]+(\.[0-9]+)?[E]([+-]?[0-9]+)$",
RegexOptions.IgnoreCase))
{
//Console.WriteLine("Regular expression matched for this :" + column);
columnDuplicate = ToLongString(Double.Parse
(column,
System.Globalization.NumberStyles.Float));
//Console.WriteLine("Converted this no in scientific notation " +
// "" + column + " to this number " +
// columnDuplicate);
if (lineCount % 1000 == 0)
{
Console.WriteLine(string.Format("processed {0} lines. still going....", lineCount));
}
}
}
catch (Exception)
{
}
duplicateLine = duplicateLine + columnDuplicate;
if (counter != lengthOfColumns)
{
duplicateLine = duplicateLine + columnDelimiter.ToString();
}
counter++;
}
outputFile.WriteLine(duplicateLine);
lineCount++;
}
}
}
Console.WriteLine("The transformed file is here :" +
outputFilePathWithoutNumbersInScientificNotation);
Console.WriteLine(#"Hit any key to exit");
Console.ReadKey();
}
}
}
}
}
An easier way would be to save it as a .csv file. Then, instead of just opening the file - you go to the Data tab and select "from text" so that you can get the dialogue box. This way you can identify that column with the scientific notation as text to wipe out that format. Import the file and then you can reformat it to number or whatever you want.

Resources