Kendo Upload- Change File Name and get it back - file-upload

I use kendo upload on my mvc project. My user have to upload files and I have to change file name with the unique file name.
I change the file name in the controller :
public ActionResult Dosyayukle(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
var fileName = Path.GetFileName(file.FileName);
var ext = Path.GetExtension(fileName);
var physicalPath = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName.Replace(ext, "") + Guid.NewGuid() + ext);
file.SaveAs(physicalPath);
}
}
// Return an empty string to signify success
return Content("");
}
I need to get file name and save this file name to db with unique name.
In JS onComplate event I can't found the file new file name.
this.onComplate = function (e) {
var dosyaAdi = self.dosyaAdi();
if (dosyaAdi.match(/rar$/)) {
alert('rar');
} else if (dosyaAdi.match(/zip$/)) {
alert('zip');
} else {
alert(dosyaAdi);
}
};
How can I pass the new file name to onComplate event handler?
Or how can I do this another way ?

You can use TempData to store key value object in which you can save file name and unique key. The same temp data you can get it in the save call.
Hope this solves your problem.

I've found a solution for your question.
http://www.telerik.com/support/kb/aspnet-ajax/editor/giving-the-uploaded-files-unique-names.aspx

Related

How to obtain information about the owner of a Dropbox shared file via the API?

I am writing an application where the users are sharing specific files via Dropbox. I am using the REST API. Lets say A shares a file to B. I know that A can share the file by adding B as a member to a file(add_file_member) and that B can check files shared with him by list_received_files. But I can't find a way that B can see who shared the file. It seems reasonable to have access to this info. Is there a way to obtain some account id or a display info for the user A from B perspective?
The SharedFileMetadata object returned by /sharing/list_received_files doesn't include this information, but I'll be sure to pass this along as a feature request.
However, you can use /sharing/list_file_members to list the members of the shared file, as well as their access level (e.g., owner, editor, etc.).
Example for C# Dropbox SDK.
public async Task<string> GetSharedFileOwnerID(Dropbox.Api.Files.Metadata data, Dropbox.Api.DropboxClient DropboxClient)
{
string owner = "";
var file = data.AsFile;
if ((file.HasExplicitSharedMembers ?? false) || (file.SharingInfo != null))
{
// search the real file owner
var list = await DropboxClient.Sharing.ListFileMembersAsync(file.Id);
var list_continue = false;
do
{
var item = list.Users.First(i => i.AccessType.IsOwner);
if (item != null)
{
owner = item.User.AccountId;
break;
}
list_continue = (list.Cursor != null);
if (list_continue)
{
list = await DropboxClient.Sharing.ListFileMembersContinueAsync(list.Cursor);
}
}
while (list_continue);
}
return owner;
}
public async Task<string> GetSharedFoldeOwnerID(Dropbox.Api.Files.Metadata data, Dropbox.Api.DropboxClient DropboxClient)
{
string owner = "";
var folder = data.AsFolder;
if (folder.SharedFolderId != null)
{
// search the real folder owner
var list = await DropboxClient.Sharing.ListFolderMembersAsync(folder.SharedFolderId);
var list_continue = false;
do
{
var item = list.Users.First(i => i.AccessType.IsOwner);
if (item != null)
{
owner = item.User.AccountId;
break;
}
list_continue = (list.Cursor != null);
if (list_continue)
{
list = await DropboxClient.Sharing.ListFolderMembersContinueAsync(list.Cursor);
}
}
while (list_continue);
}
return owner;
}
C# Dropbox SDK is NuGet package.
Use Install-Package Dropbox.Api for install it.

How to get data from database and make download that content as pdf format in Asp.net MVC

I have data in varbinary type in database from "Artifact" table like
ID CONTENT
1 Some data in varbinary type
Now i want to get the "Content" column data and should download as PDF format in Users Download folder with name "Report.PDF" file.
How should i this? I have tried like
public ActionResult DownloadFile(int fileId)
{
ResLandEntities reslandEntities = new ResLandEntities();
var content = reslandEntities.ARTIFACT.Where(m => m.ID== fileId).FirstOrDefault();
byte[] contents = content.CONTENT;
string text = Encoding.UTF8.GetString(contents);
return File(Server.MapPath("~/download/Report.PDF"), "application/pdf", text );
}
But, not getting, can anybody help me
Try This :
public ActionResult DownloadFile(int fileId)
{
ResLandEntities reslandEntities = new ResLandEntities();
var content = reslandEntities.ARTIFACT.Where(m => m.ID== fileId).FirstOrDefault();
byte[] contents = (byte[])content.CONTENT;
return File(contents, "application/pdf");
}

Localization With Database MVC

I am working on a multilingual ASP.NET MVC application (MVC4).
I want to make my resource file strings to be editable at runtime without recompiling the application and without app pool recycling And it doesn't look possible with .resx file, so I migrate to store string resources in Database.
I have to Get Each Label/String Resource From Database, so there will be more hits to database for each request. How to fix that?
I have googled around and someone suggests to load the resource in a dictionary and store it as application variable, at login/Sign In page and use that dictionary as resource instead of database hit.
I am confused, what will be effective approach.Can someone guide me in right direction to avoid more database hits?
Any help/suggestions will be highly appreciated.
Thanks
I ran into the same concerns using .resx files for localization. They just did not work well when the persons doing the translation were not programmers. Now, we have a translation page in our admin area. Works great.
One area which we still don't have a good solution for are the data annotations, which still use the .resx files. I have trimmed the source below to remove any references to our actual database structures or tables.
There is a fallback to using the underlying .resx file, if an entry does not exist in the database. If there is not an entry in the .resx file, I split the word whenever a capitol letter is found ( CamelSpace is a string extension method ).
Lastly, depending on your implementation, you may need to remove the context caching, especially if you are caching out of process.
A few examples of usage:
#LanguageDb.Translate("Enter your first name below","FirstNamePrompt")
#LanguageDb.Me.FirstName
#String
.Format(LanguageDb
.Translate(#"You can be insured for
{0} down and {1} payments of {2}"),
Model.Down,Model.NumPayments,
Model.InstallmentAmount)
public class LanguageDb : DynamicObject
{
public static dynamic Me = new LanguageDb();
private LanguageDb() { }
public static string Translate(string englishPhrase, string resourceCode = null)
{
return GetTranslation(englishPhrase, resourceCode) ?? englishPhrase;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = GetTranslation(binder.Name);
return true;
}
private static string GetTranslation(string resourceName, string resourceCode = null)
{
resourceCode = resourceCode ?? resourceName;
if (resourceCode.Contains(" ") || resourceCode.Length > 50)
{
resourceCode = resourceName.GetHashCode().ToString(CultureInfo.InvariantCulture);
}
var lang = (string)HttpContext.Current.Request.RequestContext.RouteData.Values["lang"] ?? "en";
// cache entries for an hour
var result = Get(subagent + "_" + lang + "_" + resourceCode, 3600, () =>
{
// cache a datacontext object for 30 seconds.
var context = Get("_context", 30, () => new YourDataContext()) as YourDataContext;
var translation = context.Translations.FirstOrDefault(row => row.lang == lang && row.Code == resourceCode);
if (translation == null)
{
translation = new Lookup {
Code = resourceCode,
lang = lang,
Value = Language.ResourceManager.GetString(resourceName, Language.Culture)
?? resourceName.CamelSpace()
};
context.Translations.Add(translation);
context.SaveChanges();
}
return translation.Value;
});
return result;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
// ignore this
return true;
}
public static T Get<T>(string cacheId, int secondsToCache, Func<T> getItemCallback) where T : class
{
T item = HttpRuntime.Cache.Get(cacheId) as T;
if (item == null)
{
item = getItemCallback();
if (secondsToCache > 0)
{
HttpRuntime.Cache.Insert(
cacheId, item, null, Cache.NoAbsoluteExpiration,
new TimeSpan(0, 0, secondsToCache), CacheItemPriority.Normal, null);
}
else
{
HttpRuntime.Cache.Insert(cacheId, item);
}
}
return item;
}
}

ASP.NET Bundling and minification include dynamic files from database

I'm developing a multi-tenancy MVC 4 application on which the user has some theming possibilities.
He can override every single resource (css, js, jpg, png, ect...) by adding a relative path to a theming table e.g. /Scripts/booking.js
Which tenant to use is figured out by the URL e.g. http://myapp/tenant/Booking/New this is simply the name of the connection string which should be used.
Therefore if a request is made for a specific resource I first need to check if there is an overridden version of this resource in the database and use it if found.
Now I'd like to implement the new bundling and minification features which microsoft provides in the System.Web.Optimization namespace. But I couldn't figure out how to achieve this with the files in the database.
I've prototyped my own JsMinify implementation to achieve this
public class MyJsMinify : JsMinify
{
private static byte[] GetContentFile(FileInfo filePath)
{
string fullName = filePath.FullName;
int indexOf = fullName.IndexOf("content", StringComparison.OrdinalIgnoreCase);
string substring = fullName.Substring(indexOf + 8).Replace(#"\\", "/").Replace(#"\", "/");
ThemingService themingService = ObjectFactory.GetInstance<ThemingService>();
Theming myTheming = themingService.Find(new ThemingFilter { FilePathLike = substring });
if (myTheming == null)
{
return themingService.GetContentFile(fullName);
}
return myTheming.FileData;
}
public override void Process(BundleContext context, BundleResponse response)
{
StringBuilder newContent = new StringBuilder();
foreach (FileInfo fileInfo in response.Files)
{
using (MemoryStream memoryStream = new MemoryStream(GetContentFile(fileInfo)))
{
using (StreamReader myStreamReader = new StreamReader(memoryStream, true))
{
newContent.AppendLine(myStreamReader.ReadToEnd());
}
}
}
response.Content = newContent.ToString();
base.Process(context, response);
}
}
This seems to work if I'm in Release mode but while developing I'd like to get each single script referenced independently. This is automatically done throughout the bundling and minification framework. The Resource URL's generated by the framework looks like the following
<script src="/myapp/Content/Scripts/jquery-1.9.0.js"></script>
but should look like this
<script src="/myapp/tenant/Content/Scripts/jquery-1.9.0.js"></script>
I've configured the following Routes:
routeCollection.MapRoute("Content1", "{mandator}/Content/{*filePath}", new { mandator = defaultMandator, controller = "Environment", action = "ContentFile" }, new { mandator = mandatorConstraints });
routeCollection.MapRoute("Content2", "Content/{*filePath}", new { mandator = defaultMandator, controller = "Environment", action = "ContentFile" }, new { mandator = mandatorConstraints });
The ContentFile Method looks like this
[AcceptVerbs(HttpVerbs.Get)]
[AcceptType(HttpTypes.All)]
[OutputCache(CacheProfile = "ContentFile")]
public ActionResult ContentFile(string filePath)
{
if (string.Compare(filePath, "Stylesheets/Import.css", StringComparison.OrdinalIgnoreCase) == 0)
{
return GetContentImport(CssFileArray, "Stylesheets/");
}
if (string.Compare(filePath, "Stylesheets/ImportOutlook.css", StringComparison.OrdinalIgnoreCase) == 0)
{
return GetContentImport(OutlookCssFileArray, "Stylesheets/");
}
if (string.Compare(filePath, "Scripts/OutlookAddin/Import.js", StringComparison.OrdinalIgnoreCase) == 0)
{
return GetContentImport(OutlookJsFileArray, "Scripts/");
}
return new FileContentResult(GetContentFile(filePath), MimeType(filePath));
}
Does anybody have an idea how I could achieve this?
Is there a multi-tenancy pattern to follow?
So I'm not sure I completely understand your scenario, but I believe this is what VirtualPathProviders could be used for.
We added support in the 1.1-alpha1 release, so bundles will automatically use the VirtualPathProvider registered with ASP.NET to fetch the contents of the file.
If you were to write a custom VPP that is able to always return the correct version of ~/Scripts/booking.js, everything should just work.

Copying sitecore rendering to new template programmatically using renderingDefinition.ItemId?

I have a custom sitecore button which changes the template of the current item, simple enough.
However as part of this I'm trying to also migrate the renderings of the old layout to a new layout if it's of a certain sublayout type by ItemId. However the ItemId that is returned is always null, the only value I get back from the RenderingDefinition is the UniqueId.
What am I doing wrong?
I have used this blog post as a guide.
The Code
public class ConvertToNewTemplateCommand : Command
{
protected void Run(ClientPipelineArgs args)
{
if (!SheerResponse.CheckModified())
return;
Item item = Context.ContentDatabase.Items[args.Parameters["id"]];
if (args.IsPostBack)
{
if (args.Result == "yes")
{
//Get current layout details
var originalLayoutXml = item[FieldIDs.LayoutField];
//Get new template
TemplateItem hubTemplate = Context.ContentDatabase.GetTemplate("some guid...");
//Change template
item.ChangeTemplate(hubTemplate);
//Reset laytout
ResetLayout(item);
//Get reset layout
var newLayoutXml = item[FieldIDs.LayoutField];
//Add all the module containers to the new layout in the central column
MoveModuleContainers(item, originalLayoutXml, newLayoutXml);
}
}
}
private void MoveModuleContainers(Item item, string oldXml, string newXml)
{
var oldLayout = LayoutDefinition.Parse(oldXml);
var newLayout = LayoutDefinition.Parse(newXml);
bool updated = false;
var oldRenderings = (oldLayout.Devices[0] as DeviceDefinition).Renderings;
var newRenderings = (newLayout.Devices[0] as DeviceDefinition).Renderings;
foreach (RenderingDefinition rendering in oldRenderings)
{
// Here is where the rendering.ItemID is always null
if (rendering != null && !String.IsNullOrEmpty(rendering.ItemID) && new Guid(rendering.ItemID) == new Guid("matching guid..."))
{
rendering.Placeholder = "middlecolumn";
newRenderings.Add(rendering);
updated = true;
}
}
if (updated)
{
// Save item...
}
}
}
I got onto Sitecore support in the end which informed me that I should use:
Sitecore.Data.Fields.LayoutField.GetFieldValue(item.Fields[Sitecore.FieldIDs.LayoutField])
instead of:
item[FieldIDs.LayoutField]
to get the items layoutField correctly. This results in the rendering values being parsed correctly and as they say the rest is history.