MVC Rotativa.ActionAsPdf generate Unauthorized in pdf - rotativa

Rotativa.ActionAsPdf is working fine when you have set Anonymous access true in IIS. but when you select window authentication , the Rotativa.ActionAsPdf Generate pdf with error Unauthorized etc.
google a lot could not find any solution ..
here is my solution :::
create a standard user name in your AD (Active directory) and use this user name and password to generate the file.
example
string iFilename = "eForms_" + Id + "_" + DateTime.Now.ToString("dd_mm_yyyy_hh_mm_ss") + ".pdf";
ViewBag.FileName = Server.MapPath("~" + "/Files/" + iFilename);
var iResult = new Rotativa.ActionAsPdf("displayForm", new { Id = Id }) { FileName = iFilename, SaveOnServerPath = Server.MapPath("~" + "/Files/" + iFilename) };
iResult.UserName = "genericuser";
iResult.Password = "password";
return iResult;

Related

Access to wwwroot - Asp.Net Core MVC working well on local host but not in published app

I'm having a lot of trouble trying to get my App to work when
published. Basically, the code is supposed to create a doc from
template using Open XML sdk, then save to wwwroot and then upload to
blob storage.
It's working fine using local host. Have read and tried some stuff re
accessing static files - but nothing seems to work. Any help would be
very much appreciated. Relevant code is below:
[HttpGet]
public IActionResult GenerateDocxBrowser(MemoryStream mem, string filepath, string inputLastName, string inputTitle, string requestID, string dateReceived, string complaintType, string complaintDetails, string nameString, string no, string street, string town, string postcode)
{
var list = _context.Complaints.Where(s => s.ComplaintId.ToString().Contains(requestID)).ToList();
using (mem = new MemoryStream())
{
filepath = #"wwwroot\RequestTemplate.docx";
nameString = list.Select(s => s.NameString).FirstOrDefault();
complaintDetails = list.Select(s => s.Complaint).FirstOrDefault();
street = list.Select(s => s.AddressStreet).FirstOrDefault();
town = list.Select(s => s.AddressTown).FirstOrDefault();
using (WordprocessingDocument document = WordprocessingDocument.Open(filepath,true))
{
document.GetMergeFields("LastName").ReplaceWithText(inputLastName);
document.GetMergeFields("Title").ReplaceWithText(inputTitle);
document.GetMergeFields("ComplaintID").ReplaceWithText(requestID);
document.GetMergeFields("DateReceived").ReplaceWithText(dateReceived);
document.GetMergeFields("ComplaintType").ReplaceWithText(complaintType);
document.GetMergeFields("ComplaintDetails").ReplaceWithText(complaintDetails);
document.GetMergeFields("NameString").ReplaceWithText(nameString);
document.GetMergeFields("AddressLn1").ReplaceWithText(no + " " + street);
document.GetMergeFields("AddressLn2").ReplaceWithText(town + " TAS " + postcode);
document.SaveAs(#"wwwroot\" + requestID + ".docx");
document.MainDocumentPart.Document.Save();
document.Close();
}
}
const string StorageAccountName = "xxx";
const string StorageAccountKey = "xxxxxx";
var storageAccount = new CloudStorageAccount(
new StorageCredentials(StorageAccountName, StorageAccountKey), true);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("tasman/Request Images");
CloudBlockBlob blockBlob = container.GetBlockBlobReference(requestID + ".docx");
blockBlob.UploadFromFileAsync(#"wwwroot\" + requestID + ".docx");
return View();
}
Your .SaveAs() field should be relative, currently its literally saving to wwwroot somewhere on the drive. You can specify the relative path a few different ways - one of them is below:
var saveToFolder = Path.Combine(Environment.CurrentDirectory, $"/wwwroot/{requestID}.docx");

Unable to upload files greater than 7KB via ajax call to servlet over https

I am running JBoss 6.3 portal and have deployed a war file containing following two files
1) DocUpload.jsp
Containing following code snippet making an ajax call to send the mentioned fields in data2 along with file object fd.
fd.append('file', document.getElementById('file1').files[0]);
data2 = encodeURIComponent(document.getElementById("lob").value)+'#'+encodeURIComponent(document.getElementById("loantype").value)+
'#'+encodeURIComponent(document.getElementById('docType').value)+'#'+encodeURIComponent(document.getElementById('docName').value)+
'#'+encodeURIComponent(document.getElementById('entity').value)+'#'+encodeURIComponent(document.getElementById('userName').value)+
'#'+encodeURIComponent(document.getElementById('PartyName').value)+'#'+encodeURIComponent(document.getElementById('loanAccount').value)+
'#'+encodeURIComponent(document.getElementById('LoanAmount').value)+'#'+encodeURIComponent(e4)+'#'+encodeURIComponent(document.getElementById('hiddenWIName').value)+'#'+encodeURIComponent(e3);
alert("data2 "+data2);
var ret = doPostAjax("${pageContext.request.contextPath}/AddDocumentsServlet?data="+data2,fd);
2) AddDocumentsServlet.java
Containing code for handling the request
File path = new File(RootFolderPath + File.separator + "Portal_TmpDoc" + File.separator + todayAsString + File.separator + lMilliSecondsCurrent);
UploadPath = path.getAbsolutePath();
if (!path.isDirectory()) {
path.mkdirs();
}
if (isMultipart) {
System.out.println("Inside if isMultipart");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
//List multiparts = upload.parseRequest(request);
System.out.println("Before parsing request");
List<FileItem> multiparts = upload.parseRequest(request);
System.out.println("multiparts :::"+multiparts);
for (Iterator iterator = multiparts.iterator(); iterator.hasNext();) {
FileItem item = (FileItem) iterator.next();
logger.info(item);
if (!item.isFormField()) {
String fileobject = item.getFieldName();
System.out.println(request.getParameter("data"));
String[] fileArray = request.getParameter("data").split("#");
name = new File(item.getName()).getName();
name = name.substring(name.lastIndexOf(File.separatorChar) + 1);
ext = name.substring(name.lastIndexOf(".") + 1);
logger.info(name);
File directory = new File(UploadPath);
File[] afile;
int j = (afile = directory.listFiles()).length;
for (int i = 0; i < j; i++) {
File f = afile[i];
if (f.getName().startsWith(filename))
f.delete();
}
item.write(new File(UploadPath + File.separator + filename + "." + ext));
System.out.println("File Uploaded");
}
}
My problem is when I use http connection for the above requests and getting session the program runs just fine. But while using https and uploading file greater than 7 KB the page becomes unresponsive.
On further analysis I found that the program flow gets stuck on this line
List<FileItem> multiparts = upload.parseRequest(request);
and despite having this line in a try block no exception is caught.

Using the API licenseCloud, and incoporating it with your aps and web pages

I tried using the licenseCloud API but was una ble to get it right, the only guess I came to was the fact that I obtained an XML and a link to that XML "https://secure.licenseapi.com/?token=73af9d231e354e2c9ba30a72fdc68341b88613c1&sku=EXAMPLE&license=e59d6fd6629044f4ace4", so I took the link, placed in a textbox and on a buttonclick fires.
XDocument csvDocument = XDocument.Load(txtActivateFromSite.Text);
var samples = csvDocument.Descendants("license")
.Select(el => new
{
Id = el.Element("dashed").Value,
Selected = el.Element("status").Value,
Selected1 = el.Element("trial").Value,
Selected2 = el.Element("expires").Value,
Selected3 = el.Element("activated").Value
});
string dashed = ""; string status = ""; string trial = ""; string expires = ""; string activated = "";
foreach (var sample in samples)
{
dashed = sample.Id;
status = sample.Selected;
trial = sample.Selected1;
expires = sample.Selected2;
activated = sample.Selected3;
}
MessageBox.Show("your Application has been activate with License Number " + dashed + " on " + activated + " expires on "+
expires + ".");
Somehow I incoporated it to get something, please anymore ideas on how to use licensecloud
Appears you've forgotten the CMD parameter on your link:
&cmd=activate...
Also, you can download some sample code here (in PHP). Will give you a good idea on how to get it to work:
https://www.licensecloud.com/2015/04/10/licensecloud-protect-web-page/

How to get the Uploaded Files in MVC3?

Hi all i am uploading the files uploaded by the user in this path
string savefilename = Path.Combine(Server.MapPath("~/Content/UploadedFiles/"),
Path.GetFileName());
And i am saving the Url in the Database in the Url Column in this
~/Content/UploadedFiles/BugTrackerDataBase.xlsx
and i am trying to retrieve the file Uploaded by the user by a link in my grid view
my retrieve method looks like this
public ActionResult ViewAttachments(string AttachmentName)
{
try
{
AttachmentName = Session["AttachmentUrl"].ToString();
var fs = System.IO.File.OpenRead(Server.MapPath("'" + AttachmentName + "'"));
return File(fs, "application/doc", AttachmentName);
}
catch
{
throw new HttpException(404, "Couldn't find " + AttachmentName);
}
}
and i have the Excepiton
"Could not find a part of the path 'D:\AnilWork\BugTracker\BugTracker\ViewBug\'UploadedFiles\BugTrackerDataBase.xlsx''."
can any one tell me where am i doing wrong or the write procedure to do this
That is because you have " ' " in your path.
\BugTracker\ViewBug\'UploadedFiles\BugTrackerDataBase.xlsx''
Remove them an it should work. Like this
var fs = System.IO.File.OpenRead(Server.MapPath(AttachmentName));
try
var fs = System.IO.File.OpenRead(Server.MapPath(" + AttachmentName + "));
instead of
var fs = System.IO.File.OpenRead(Server.MapPath("'" + AttachmentName + "'"));
it shoud be replaced with (Server.MapPath(""+ AttachmentName + ""))

How can I get the Exchange Server programmatically from my App(C#)

Currently I can send email successfully through WebDAV with C#, but there is a shortage in my App that I have hard-code the Exchange Server of my outlook, so it might only works for me, if it were moved to another PC and use another outlook account, it might not work because the Exchange Server for this outlook account might not the same as mine(that's beacuse our company for different email account might assign different Exchange server), so my question is that how can I get the Exchange Server for the current Email accout dynamically. In fact I can get this Exchange Server from the outlook client when I clicked the menu item to add a new Outlook Account, but dose there exist any API for me to get this Exchange Server programmatically such as with C#?
In fact I use the following code to send Email:
using System;
using System.Net;
using System.IO;
namespace WebDavNET
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
try
{
// TODO: Replace with the name of the computer that is running Exchange 2000.
string strServer = "ExchServe";
// TODO: Replace with the sender's alias.
string strSenderAlias = "sender";
// TODO: Replace with the sender's e-mail address.
string strFrom = "sender#example.com";
// TODO: Replace with the recipient's e-mail address.
string strTo = "recipient#example.com";
string strSubject = "Send Using HttpWebRequest";
string strBody = "Hello World";
string sUri;
sUri = "http://" + strServer + "/Exchange/" + strSenderAlias;
sUri = sUri + "/%23%23DavMailSubmissionURI%23%23/";
System.Uri myUri = new System.Uri(sUri);
HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(myUri);
string sQuery;
DateTime mySentTime = new DateTime();
sQuery = "From: " + strFrom + "\n" +
"To: " + strTo + "\n" +
"Subject: " + strSubject + "\n" +
"Date: " + DateTime.Now.ToString() + "\n" +
"X-Mailer: My DAV mailer" + "\n" +
"MIME-Version: 1.0" + "\n" +
"Content-Type: text/plain;" + "\n" +
"Charset = \"iso-8859-1\"" + "\n" +
"Content-Transfer-Encoding: 7bit" + "\n" + "\n" +
strBody;
// Set the credentials.
// TODO: Replace with the appropriate user credential.
NetworkCredential myCred = new NetworkCredential(#"DomainName\User", "Password");
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myCred);
HttpWRequest.Credentials = myCredentialCache;
// Set the headers.
HttpWRequest.Headers.Set("Translate", "f");
HttpWRequest.ContentType = "message/rfc822";
HttpWRequest.ContentLength = sQuery.Length;
//Set the request timeout to 5 minutes.
HttpWRequest.Timeout = 300000;
// Set the request method.
HttpWRequest.Method = "PUT";
// Store the data in a byte array.
byte[] ByteQuery = System.Text.Encoding.ASCII.GetBytes(sQuery);
HttpWRequest.ContentLength = ByteQuery.Length;
Stream QueryStream = HttpWRequest.GetRequestStream();
// write the data to be posted to the Request Stream
QueryStream.Write(ByteQuery,0,ByteQuery.Length);
QueryStream.Close();
// Send the request and get the response.
HttpWebResponse HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();
// Get the Status code.
int iStatCode = (int)HttpWResponse.StatusCode;
string sStatus = iStatCode.ToString();
Console.WriteLine("Status Code: {0}", sStatus);
// Get the request headers.
string sReqHeaders = HttpWRequest.Headers.ToString();
Console.WriteLine(sReqHeaders);
// Read the response stream.
Stream strm = HttpWResponse.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string sText = sr.ReadToEnd();
Console.WriteLine("Response: {0}", sText);
// Close the stream.
strm.Close();
// Clean up.
myCred = null;
myCredentialCache = null;
HttpWRequest = null;
HttpWResponse = null;
QueryStream = null;
strm = null;
sr = null;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
}
As you can see in the code there is a variable named "strServer", In my App I just hard-code my Exchange Server for this variable, so my question is that dose there exist any API for me to get the Exchange Server dynamically for the specific outlook account?
Thanks!
You can use EWS(exchange Web Services) too. here is the link
You can use XML creator for creating items or requests required for operations in the link. Just go through the operations given on the link.

Resources