Kentico 10 - Files not synced to AWS S3 - amazon-s3

We are trying to integrate AWS S3 in our Kentico 10 application.
I followed this link:
https://docs.xperience.io/k10/custom-development/working-with-physical-files-using-the-api/configuring-file-system-providers/configuring-amazon-s3#ConfiguringAmazonS3-Medialibrarynotes
I created following module in App_Code => CMSModules => AWSS3 => AWSS3Module.cs
Here is the code of AWSS3Module.cs
using CMS;
using CMS.DataEngine;
using CMS.EventLog;
using CMS.IO;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
/*
Make sure following entries exists in web.config => <appSettings>
<add key="CMSAmazonBucketName" value="" />
<add key="CMSAmazonAccessKeyID" value="" />
<add key="CMSAmazonAccessKey" value="" />
<add key="CMSAmazonPublicAccess" value="true" />
<add key="CMSAmazonEndPoint" value="" />
*/
[assembly: RegisterModule(typeof(AWSS3Module))]
/// <summary>
/// Summary description for AWSS3Module
/// </summary>
public class AWSS3Module: Module
{
public AWSS3Module(): base("AWSS3Module")
{
//
// TODO: Add constructor logic here
//
}
// Initializes the module. Called when the application starts.
protected override void OnInit()
{
base.OnInit();
// Assigns a handler to the Insert.After event for OfficeInfo objects
EventLogProvider.LogInformation("AWSS3 module", "OnInit", "This code is running");
// Creates a new StorageProvider instance
AbstractStorageProvider mediaProvider = new StorageProvider("Amazon", "CMS.AmazonStorage");
// Specifies the target bucket
mediaProvider.CustomRootPath = ConfigurationManager.AppSettings["CMSAmazonBucketName"];
// Makes the bucket publicly accessible
mediaProvider.PublicExternalFolderObject = true;
// Maps a directory to the provider
StorageHelper.MapStoragePath("~/Sitename/", mediaProvider);
}
}
I read in one of the post that only new files will be synced. I tried adding few files in the media folder but nothing added in bucket.
There are no errors in logs. Also, I can see the module is loaded in the logs.
Bucket policy seems to be correct or I couldn't find issues in logs.
What am I doing wrong?
Also, if a file is uploaded, how can I get the S3 URL for that file?

Check this section:
StorageHelper.MapStoragePath("~/Sitename/", mediaProvider);
Make sure "/Sitename/" is the actual folder the media lib uses!
All you do here is basically instruct Kentico that there is an "alternative" way of storing files in folder 'x'. If your media lib is not storing in that exact folder it doesn't do anything.

Related

DisplayNameFor doesn't lookup resx file despite IStringLocalizer and IHtmlLocalizer working correctly in the Razor page

I've got my Login.cshtml page
#page
#using Microsoft.AspNetCore.Mvc.Localization
#using Microsoft.Extensions.Localization
#inject IStringLocalizer<LoginModel> localizer
#inject IHtmlLocalizer<LoginModel> htmlLocalizer
#model LoginModel
<h1>#htmlLocalizer["Title"]</h1> TRANSLATES WELL
<h1>#localizer["Title"]</h1> TRANSLATES WELL
[...]
div class="checkbox">
<label asp-for="Input.RememberMe" class="form-label">
<input class="form-check-input" asp-for="Input.RememberMe" />
#Html.DisplayNameFor(m => m.Input.RememberMe) //DOESN'T WORK, DOESN'T LOOKUP RESX FILE
</label>
</div>
In the scaffolded Login.cshtml.cs page model there is an attribute [Display] fr the RememberMe property, but this one is not getting translated despite translation being put in the same resource file
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[Display(Name = "Remember")] //DOESN'T WORK, DOESN'T LOOKUP RESX FILE
public bool RememberMe { get; set; }
We can see that the structure is correct
Resx file itself:
This is what gets rendered:
Add data annotations localization in startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddDataAnnotationsLocalization(options => {
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResource));
});
}
This is Microsoft's bug which I reported: https://developercommunity.visualstudio.com/t/Custom-tool-cant-generate-designer-file/10213747?
Steps to reproduce:
Create ASP.Net Core MVC app Create resources directory Create resource
file called name.pl.resx Add few keypairs Build Expected behaviour:
Designer file is generate the resx file can be referenced as a type in
the code.
Actual behaviour: Error: Custom tool PublicResXFileCodeGenerator
failed to produce an output for input fileā€¦
Workaround: With each resx file edition
remove locale from its name Unload projectt Releoad project Clean
Build Rename resx file to contain locale again

Sap.Data.SQLAnywhere.SAException: Cannot find the language resource file (dblgen17.dll) when connecting to Sybase SQL Anywhere using .NET

I am trying to establish a connection to a Sybase database, using Sap.Data.SQLAnywhere. Using an SQL Anywhere client works perfect from a workstation, but I am having some trouble running the code within an Azure Function.
This is the beginning of my simple code:
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using System.Data.SqlClient;
using Microsoft.Extensions.Logging;
using System;
using Sap.Data.SQLAnywhere;
namespace SBCTest
{
public static class SybaseTest
{
static string DB_CS_SOURCE = "Host=myIP;UID=myUID;PWD=myPWD;Data Source=myDb;"; static int bulkSize = 5000;
[FunctionName("SybaseTest")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
{
try
{
var dbSourceCon = new SAConnection()
dbSourceCon.ConnectionString = DB_CS_SOURCE;
dbSourceCon.Open();
//etc... etc...
The problem I am facing, which I can't seem to manage is the following error I get when running the app:
[Error] System.TypeInitializationException: The type initializer for 'Sap.Data.SQLAnywhere.SAConnection' threw an exception. ---> Sap.Data.SQLAnywhere.SAException: Cannot find the language resource file (dblgen17.dll).
at Sap.Data.SQLAnywhere.SAUnmanagedDll..ctor()
at Sap.Data.SQLAnywhere.SAUnmanagedDll.get_Instance()
at Sap.Data.SQLAnywhere.SAConnection..cctor()
--- End of inner exception stack trace ---
at Sap.Data.SQLAnywhere.SAConnection..ctor()
at SBCTest.SybaseTest.<Run>d__3.MoveNext()
dblgen17.dll is included in the SAP SQL Anywhere Database Client found here, and has been added to my project, with Build Action set to None, and Copy to Output Directory set to Copy Always.
The "missing file" dblgen17.dll can be found in /site/wwwroot/bin after publish, as expected, along with Sap.Data.SQLAnywhere.v4.5.dll.
Why does it still say that it's missing? My Google results point me to the fact that it might have something to do with the PATH variable, but since this is an Azure Function I'm not sure what to do here.
I also noted an additional, odd behavior, described below.
Sometimes, sporadically when re-publishing a non-altered code, I can also get this error message all of a sudden:
[Error] Sap.Data.SQLAnywhere.SAException (0x80004005)
at Sap.Data.SQLAnywhere.SAConnection.Open()
at SBCTest.SybaseTest.<Run>d__3.MoveNext()
How can I make my code recognize the file, and hopefully connect successfully?
In my case, it worked out by reseting IIS, this can be done via cmd, with the iisreset command.
Here's the solution that I found based on this SO answer and it actually worked!
/// <summary>
/// Updates PATH variable in hosting instance to allow referring to items in this project's /bin folder.
/// Very helpful with Azure.
/// </summary>
public static void CheckAddBinPath()
{
// find path to 'bin' folder
var binPath = Path.Combine(new string[] { AppDomain.CurrentDomain.BaseDirectory, "bin" });
// get current search path from environment
var path = Environment.GetEnvironmentVariable("PATH") ?? "";
// add 'bin' folder to search path if not already present
if (!path.Split(Path.PathSeparator).Contains(binPath, StringComparer.CurrentCultureIgnoreCase))
{
path = string.Join(Path.PathSeparator.ToString(), new string[] { path, binPath });
Environment.SetEnvironmentVariable("PATH", path);
}
}
Then in Application_Start
// Sometimes files aren't loaded properly from bin. Hint to the app to load from /bin, too.
CheckAddBinPath();

WFFM Image Uploaded event Sitecore 8

I have to execute some custom operations once the WFFM File Upload Item is uploaded in Sitecore Media Library.
How I can get the uploaded WFFM media Item in C#.
Which Event/Processor/Pipeline/Config needs to add/update .
I am using below code , it works when i uploaded media manually but not when media comes from Web form Marketer:-
public class ProcessMedia : UploadProcessor
{
public void Process(UploadArgs args)
{
}
}
You can add a custom processor to the formUploadFile pipeline, the default definition of which can be found in Sitecore.Forms.config.
public class ProcessMedia
{
public void Process(FormUploadFileArgs args)
{
var itemUri = ItemUri.Parse(args.Result);
var item = Sitecore.Data.Database.GetItem(itemUri);
// do some stuff...
}
}
And then patch your processor in:
<sitecore>
<pipelines>
<formUploadFile>
<processor type="MyCustomProject.Forms.Pipelines.ProcessMedia, MyCustomProject.Forms" />
</formUploadFile>
</pipelines>
</sitecore>
The processor will be patched in after Sitecore.Form.Core.Pipelines.FormUploadFile.Save which is the pipeline responsible for saving files to the Media Library in WFFM.

How can we enable caching for Bundles in MVC5

I have created 2 bundles in my mvc project as given below:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/Scripts/BaseScripts").Include(
"~/Content/js/jquery-{version}.js",
"~/Content/js/jquery-ui-{version}.js",
"~/Scripts/jquery.unobtrusive-ajax.min.js",
"~/Content/js/bootstrap.js",
"~/Content/js/bootstrap-datepicker.js",
"~/Scripts/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/customvalidation.js"
)
);
bundles.Add(new ScriptBundle("~/Scripts/CustomScripts").Include(
"~/Content/js/customscripts/commonscript.js",
"~/Content/js/customscripts/registration.js"
));
bundles.Add(new StyleBundle("~/Styles/Css").Include(
"~/Content/css/bootstrap.min.css",
"~/Content/css/ymobiz.css",
"~/Content/css/Style.css",
"~/Content/css/datepicker3.css",
"~/Content/font-awesome-4.1.0/css/font-awesome.min.css",
"~/Content/css/css.css"
));
//To enable bundling and minification
BundleTable.EnableOptimizations = true;
}
Now i need to enable caching for these files as well. Is there any way by which we can control caching duration for these bundles files
MVC bundles are returned as a single static file to browsers whose cache time is set to 1 year by default. ASP.NET MVC takes care of change tracking of your bundle files and changes bundle url if content of any file is changed or a file is being added / removed from bundle.
As bundles are already cached and change tracking is maintained by asp.net mvc framework, what else cache control do you want on those bundles?
EDIT (in response to comment)
Unfortunately you can not alter that limit. Cache limit is handles by ProcessRequest method of BundleHandler class and this is internal sealed so there is no chance that you can inherit \ override these requests.
For further details you can refer this question.
Add a key in webconfig
<appSettings>
<add key="Version" value="sa291988" />
</appSettings>
Create a class, where we define the format for both JavaScript and styles.
using System.Configuration;
namespace BundlingSample
{
public class SiteKeys {
public static string StyleVersion {
get {
return "<link href=\"{0}?v=" +
ConfigurationManager.AppSettings["version"] + "\" rel=\"stylesheet\"/>";
}
}
public static string ScriptVersion {
get {
return "<script src=\"{0}?v=" +
ConfigurationManager.AppSettings["version"] + "\"></script>";
}
}
}
}
#Styles.RenderFormat(SiteKeys.StyleVersion,"~/Content/css")
#Scripts.RenderFormat(SiteKeys.ScriptVersion,"~/bundles/jquery")

The Role Manager feature has not been enabled but its enabled in config

I have created the following class for customized roleProvider in a folder called providers within my web project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Project.Providers
{
public class MyCustomRoleProvider : System.Web.Security.SqlRoleProvider
{
public override string[] GetRolesForUser(string username)
{
string[] currentUserRoles = { "Admin", "User" };
return currentUserRoles;
}
}
}
I have added the following section in the web.config:
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="Project.Provider.MyCustomRoleProvider, MetaLearning"/>
</providers>
</roleManager>
When I try to add the following code on my home controller:
Roles.AddUserToRole("username","role");
I am receiving an error that The Role Manager feature has not been enabled. What am I doing wrong?
Sometimes there are two web.config file in our project.Like in MVC4 internet application project one belongs in views folder This is not the configuration file for your application. It contains the configuration required to make views work with ASP.NET.
Make sure you implement your requirements in correct web.config file.