CKEditor file upload doesn't work properly with mvc 6 - ckeditor

I'm trying to use the built in upload file of CKEditor, it works with my MVC5 project, but it doesn't work with my MVC6 project, the code for uploading the file is correct, I've tested it, and it actually upload the file to the server, but it doesn't populate the form with the URL and image information, here's the code for my MVC5 project that works:
public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.ContentLength > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + Path.GetFileName(upload.FileName);
var vFolderPath = Server.MapPath("/Upload/");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
upload.SaveAs(vFilePath);
vImagePath = Url.Content("/Upload/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch(Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And here is the code for MVC6 project that doesn't work:
public async Task<ActionResult> UploadImage(IFormFile upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.Length > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + ContentDispositionHeaderValue.Parse(upload.ContentDisposition).FileName.Trim('"');
var vFolderPath = Path.Combine(_environment.WebRootPath, "Files", "ArticleUploads");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
await upload.SaveAsAsync(vFilePath);
vImagePath = Url.Content("/Files/ArticleUploads/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch (Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And in CKEditor config file I have:
config.filebrowserImageUploadUrl = '/Admin/Article/UploadImage';
I've inspected the variables, and they send the same value, also worth to note that I'm using the same version of CKEditor, so that can't be the problem, I'd appreciate any help on this.

If the file gets uploaded and you don't see the image gets populated, I guess there should be some problem with the way you return your content, since you are returning html, try to specify your content type, like so:
return Content(vOutput, "text/html");
If that didn't solve your problem, you need to provide more information, tell us what exactly you get from this action in JavaScript side.

Related

Email body returns a blank or null in chilkat mail

I have the following code that reads a bunch of emails from a folder. It gets the emails fine, as I can see the number of emails are correct and the header is correct as well.
However it returns nothing for the body. I do have a email with simple text as well but that too does not return anything. Part of the code is below.
any help is appreciated. the account I am reading is from a office 365 and i used the imap.Connect
(*i can read these emails from the Microsoft Outlook, so i think the issue is with my chilkat code)
Chilkat.MessageSet messageSet = imap.Search(#"ALL", fetchUids);
if (imap.LastMethodSuccess == false)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + imap.LastErrorText;
return;
}
// Fetch the email headers into a bundle object:
Chilkat.EmailBundle bundle = imap.FetchHeaders(messageSet);
if (imap.LastMethodSuccess == false)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + imap.LastErrorText;
return;
}
// Sort the email bundle by date, recipient, sender, or subject:
bool ascending = true ; bool descending = true;
bundle.SortByDate(ascending);
//bundle.SortByDate(descending);
// To sort by recipient, sender, or subject, call
// SortBySender, SortByRecipient, or SortBySubject.
// Display the Subject and From of each email.
int i = 0;
string body="";
while (i < bundle.MessageCount)
{
Chilkat.Email email = null;
email = bundle.GetEmail(i);
txtOutput.Text = txtOutput.Text + Environment.NewLine + Environment.NewLine + email.GetHeaderField("Date");
//Debug.WriteLine(email.GetHeaderField("Date"));
//Debug.WriteLine(email.Subject);
txtOutput.Text = txtOutput.Text + Environment.NewLine + email.From;
//Debug.WriteLine(email.From);
//Debug.WriteLine("--");
if (email.HasHtmlBody())
{
body = email.GetHtmlBody() + String.Empty;
}
else if (email.HasPlainTextBody())
{
body = email.GetPlainTextBody() + String.Empty;
}
else
{
body = email.Body + String.Empty;
}
txtOutput.Text = txtOutput.Text + Environment.NewLine + body.Trim() ;
i = i + 1;
}
You downloaded headers-only:
Chilkat.EmailBundle bundle = imap.FetchHeaders(messageSet);
Of course there is no body...

how to add a folder in the apk

I wanna to know how to add a folder in the apk.don't give me a solution about using the compress software directly. The apk was recompiled by the 'apktool.jar'. I need some code to achieve this problem. Hope one can solve my question as soon as possible.Thank you~
public static int zipMetaInfFolderToApk(String apkName, String folderName) throws IOException {
if(!new File(apkName).exists()){
return ConstantValue.ISQUESTION;
}
String zipName = apkName.substring(0, apkName.lastIndexOf(".")) + "."
+ "zip";
String bak_zipName = apkName.substring(0, apkName.lastIndexOf("."))
+ "_bak." + "zip";
FileUtils.renameFile(apkName, zipName);
ZipFile war = new ZipFile(zipName);
ZipOutputStream append = new ZipOutputStream(new FileOutputStream(
bak_zipName));
Enumeration<? extends ZipEntry> entries = war.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
System.out.println("copy: " + e.getName());
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(war.getInputStream(e), append);
}
append.closeEntry();
}
String name = "";
if(folderName.equals("")){
name = "META-INF/" + folderName;
}else{
name = "META-INF/" + folderName + "/";
}
ZipEntry e = new ZipEntry(name);
try{
append.putNextEntry(e);
}catch(ZipException e1){
append.closeEntry();
war.close();
append.close();
FileUtils.renameFile(zipName,apkName);
FileUtils.deleteFolder(bak_zipName);
e1.printStackTrace();
return ConstantValue.ISQUESTION;
}
append.closeEntry();
war.close();
append.close();
FileUtils.deleteFolder(zipName);
FileUtils.renameFile(bak_zipName, apkName);
return ConstantValue.ISNORMAL;
}

Asp.net MVC TempData Getting Crossed / Mixed Up

I have used TempData to pass data between controllers. If two users are working on the same page, User2 will get the tempdata value which is created by User1.
Below you can find the code.
Can you please help me to solve this issue.
VDRController.cs
public ActionResult RedirectToCDR(long VslMoveId, long VslVisitId, string VslNm, string ETDDtTmLoc, string statusCd)
{
//List<long> vslIds = new List<long>();
string vslIds = VslMoveId + "," + VslVisitId.ToString() + "," + statusCd;
TempData["VslMoveDetails"] = vslIds;
//DateTime MyDateTime;
//MyDateTime = new DateTime();
var strdatetime = Convert.ToDateTime(ETDDtTmLoc).ToString("dd-MMM-yyyy");
TempData["VslNameETD"] = VslNm + " " + strdatetime;
//return RedirectToAction("Index","VesselVisit");
return Json(Url.Action("Index", "CDR"));
}
CDRController.cs
public ActionResult Index()
{
if (TempData["VslMoveDetails"] != null)
{
string vslIds = TempData["VslMoveDetails"].ToString();
string[] Ids = vslIds.Split(new char[] { ',' });
if (Ids.Length == 3 && Ids[0] != null && Ids[1] != null)
{
ViewBag.VslMove_Id = Ids[0];
ViewBag.VslVisit_Id = Ids[1];
ViewBag.VisitStatus_Cd = Ids[2];
}
}
return View();
}
thanks in advance.
Your pages are being cached by IIS. For MVC applications you will need to add .cshtml to the list of file extensions that are not allowed to cache. Please see the following link for the solution to stop caching. (http://lionsden.co.il/codeden/?p=446)

AD with LDAP connection error

Im trying to use a .net application but the application cant find the server in my local network.
Im using LdapExploreTool 2 with the following settings:
the base DN is "DC=exago,DC=local", the Ip address "192.168.1.250" and the server name "exago.local"
The connection is successful and this is the result:
Inputing the values:
Examining the code, i get the exception when "Bind to the native AdsObject to force authentication":
"The specified domain either does not exist or could not be contacted."
public bool IsAuthenticated(string domain, string ldapPath, string username, string pwd, string userToValidate)
{
string domainAndUsername = domain + #"\" + username;
if (string.IsNullOrEmpty(ldapPath))
SetLdapPath(domain);
else
_path = ldapPath;
App.Services.Log.LogUtils.WriteLog(Log.LogLevel.INFO, "IsAuthenticated_DirectoryEntry:" + _path + "," + domainAndUsername + "," + pwd);
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
//check if domain is valid
int domainId = AppDomains.GetDomainIdByName(domain);
if (domainId == int.MinValue)
{
return false;
}
AppDomains d = AppDomains.GetRecord(domainId);
List<AppDomainQueries> lQueries = new List<AppDomainQueries>(AppDomainQueries.GetArray());
lQueries = lQueries.FindAll(delegate(AppDomainQueries dq) { return dq.DomainId == domainId && dq.Status == 'A'; });
string queryString = string.Empty;
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
string ldapAndQuerie = string.Empty;
//base account search
queryString = "(SAMAccountName=" + userToValidate + ")";
if (username != userToValidate)
{
if (lQueries.Count == 1)
ldapAndQuerie = lQueries.FirstOrDefault().QueryString;
if ((ldapAndQuerie != string.Empty) && (ldapAndQuerie != "*") && (ldapAndQuerie != "(objectClass = user)"))
queryString = "(&(SAMAccountName=" + userToValidate + ")" + ldapAndQuerie + ")";
}
search.Filter = queryString;
App.Services.Log.LogUtils.WriteLog(Log.LogLevel.INFO, "LDAP=" + queryString);
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
// Update the new path to the user in the directory
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
App.Services.Log.LogUtils.WriteLog(Log.LogLevel.ERROR, "App.Services.Core.LdapAuthentication.IsAuthenticated() Exception - (LDAP=" + queryString + ")" + ex.Message, ex);
return false;
}
return true;
}
How can i establish a connection?
The problem was the LDAP connection string,
it seems that it missed the actual location(IP + port) in the network.
LDAP://192.168.1.250:389/DC=exago,DC=local

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 + ""))

Resources