Report localization in Telerik self hosted service (.trdx) - asp.net

I have telerik REST web API(ASP.NET ) which is working fine. Now I need to localize the reports (report are in .trdx extension).
From documentation of telerik I found the code which have place in my BaseTelerikReportsController but this also not working, and even not show any error.
Telerik Localization Documentation
public class BaseTelerikReportsController : ReportsControllerBase
{
static readonly Telerik.Reporting.Services.ReportServiceConfiguration ConfigurationInstance;
static BaseTelerikReportsController()
{
var resolver = new CustomReportResolver();
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("aa-iq"); //<-- Line 1
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo; //<-- Line 2
var reportsPath = HttpContext.Current.Server.MapPath("~/Reports");
ConfigurationInstance = new Telerik.Reporting.Services.ReportServiceConfiguration
{
HostAppId = "TBReportApp",
ReportResolver = resolver,
// ReportResolver = new ReportFileResolver(reportsPath),
Storage = new Telerik.Reporting.Cache.File.FileStorage(),
};
}
public BaseTelerikReportsController()
{
ReportServiceConfiguration = ConfigurationInstance;
}
}
Note
There is a similar question but don't guide me to any right direction Here
Update 1
I have added below function in Global.asax.cs.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("ar");
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
// Set the language for dynamic text (i.e. date, time, money)
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
}
After above line (see image) data under red mark is localize but i need to localize yellow one(i.e heading)

I figure out how to localize the report header. Following are the some summarized steps.
Add App_GlobalResources folder and .resx accordingly your languages (See the figure 1-1).
Send language attribute from 'HTML5 Viewer'.
var viewer = $("#report-viewer").data("telerik_ReportViewer");
var model = {
//other attributes
Language: this.selectedLanguage //Here value may be ,en Or ar
};
viewer.reportSource({
report: reportSettings,
parameters: model
});
On server side based on that attribute change label accordingly.
private static void Localization(ref Report reportInstance)
{
ResourceManager currentResource = null;
switch (_language)
{
case "en":
currentResource = new ResourceManager("Resources.en", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
case "ar":
currentResource = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
}
// var MyResourceClass = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
ResourceSet resourceSet = currentResource.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string key = entry.Key.ToString();
string value = entry.Value.ToString();
var items = reportInstance.Items.Find(key,true);
foreach (var singleItem in items)
{
var singleItemType = singleItem.GetType();
//if (singleItem.GetType().FullName == "") ;
if (singleItemType.FullName == "Telerik.Reporting.TextBox")
{
var castItem = (Telerik.Reporting.TextBox) singleItem;
castItem.Value = value;
}
}
}
}
On Telerik Standalone Report Designer
Change your report(.trdx) Textbox value which matches your .resxname value pair.
Resource file values

Related

Xamarin Forms - Create Entry or Picker dynamically based on a property and bind it to a ObservableCollection object

I have a xamarin forms application that receives data from the database. The database gives "Car" data back. Those objects all have a couple of properties. On of those properties decides what kind of view should be shown on the screen. So a car could have a property named "TypeOfView" with a value "Entry" or "Picker" etc..
The problem is a follows: How can I dynamically create views based on that property and how can that be bind to objects in a list in the viewmodel?
// This is the codebehind where UI controls get created
BindingContext = DependencyInjectionService.Get<CheckListEditViewModel>();
var stack = new StackLayout()
{
Orientation = StackOrientation.Vertical,
Padding = 5
};
for (int i = 0; i < (BindingContext as CheckListEditViewModel).CheckListItems.Count; i++)
{
var item = (BindingContext as CheckListEditViewModel).CheckListItems[i];
var description = new Label()
{
Text = item.Description
};
stack.Children.Add(description);
if ((item.ChecklistItemType == Domain.ChecklistItemType.Number))
{
var numerEntry = new Entry();
numerEntry.Keyboard = Keyboard.Numeric;
numerEntry.TextChanged += MyMethod;
numerEntry.SetBinding(Entry.TextProperty, new Binding(mode: BindingMode.TwoWay, path: "Value", source: item));
stack.Children.Add(numerEntry);
// this is to test if the binding worked
var testLabelBindingTesting = new Label();
testLabelBindingTesting.SetBinding(Label.TextProperty, new Binding(mode: BindingMode.TwoWay, path: "Value", source: item));
stack.Children.Add(testLabelBindingTesting);
}
else if ((item.ChecklistItemType == Domain.ChecklistItemType.Email))
{
var numerEntry = new Entry();
numerEntry.Keyboard = Keyboard.Email;
stack.Children.Add(numerEntry);
}
}
Content = stack;
// The list is in the viewmodel class:
public ObservableCollection<ChecklistItem> CheckListItems { get; set; }

Xamarin.Forms Directory Picker

I would like to save a file in a user selected folder, thats why I would like to provide a directory list to user and user will be able to choose the directory where he wants to export the data. Unfortuntely I could not find any example for directory/folder picker, I just found a file picker which is not useful for me..
https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows
Is there any component for picking a folder for Xamarin.Forms? Actually I am just doing for Android but we use Xamarin.forms
There is none I can think of.
With netstandard everything is way more simple as you can use the classic c# File api to get the folders.
You just have to know the mappings between special folders and android folders (per example):
System.Environment.SpecialFolder Path
ApplicationData INTERNAL_STORAGE/.config
Desktop INTERNAL_STORAGE/Desktop
LocalApplicationData INTERNAL_STORAGE/.local/share
MyDocuments INTERNAL_STORAGE
MyMusic INTERNAL_STORAGE/Music
MyPictures INTERNAL_STORAGE/Pictures
MyVideos INTERNAL_STORAGE/Videos
Personal INTERNAL_STORAGE
source: https://learn.microsoft.com/en-US/xamarin/android/platform/files/
same for ios:
https://learn.microsoft.com/en-US/xamarin/ios/app-fundamentals/file-system
But it's really easy to implement, just enumerate all folders and display them in a ListView.
EDIT: more details on implementation.
In fact you want to code a "directory explorer", it's easy, here is the concept.
You have a ListView in your Page
You have a Cancel button and a Select button in your Page
You have a CurrentPath in your ViewModel
You bind CurrentPath to the Title of your Page
You have an List<DirectoryViewModel> Directories in your ViewModel
Each time a user click on a item from the list:
You add the directory name in your current path
You get all the directories from the new path, and update your Directories property (don't forget RaisePropertyChange(nameof(Directories)))
The ListView will be updated accordingly
Each time you back:
You remove last part of your current path
same as before
If you arrive to root path "/", you do nothing when clicking on back.
Oh and you could use this Grid component to instead of the ListView, will be nicer ;)
https://github.com/roubachof/Sharpnado.Presentation.Forms#grid-Layout
You can edit this to make it work..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.IO;
using Java.Util;
namespace Android.Basic.IO
{
public class DirectoryPicker : ListActivity
{
public const String START_DIR = "startDir";
public const String ONLY_DIRS = "onlyDirs";
public const String SHOW_HIDDEN = "showHidden";
public const String CHOSEN_DIRECTORY = "chosenDir";
public const int PICK_DIRECTORY = 43522;
private File dir;
private Boolean showHidden = false;
private bool onlyDirs = true;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
Bundle extras = Intent.Extras;
dir = OS.Environment.ExternalStorageDirectory;
if (extras != null)
{
String preferredStartDir = extras.GetString(START_DIR);
showHidden = extras.GetBoolean(SHOW_HIDDEN, false);
onlyDirs = extras.GetBoolean(ONLY_DIRS, true);
if (preferredStartDir != null)
{
File startDir = new File(preferredStartDir);
if (startDir.IsDirectory)
{
dir = startDir;
}
}
}
SetContentView(Resource.Layout.folder_chooser_activity);
var title = dir.AbsolutePath.ToString();
Title = (title);
Button btnChoose = (Button)FindViewById(Resource.Id.btnChoose);
String name = dir.Name;
if (name.Length == 0)
name = "/";
btnChoose.Text = ("Choose " + "'" + name + "'");
btnChoose.Click += delegate
{
returnDir(dir.AbsolutePath);
};
ListView lv = this.ListView;
lv.TextFilterEnabled = (true);
if (!dir.CanRead())
{
Context context = ApplicationContext;
String msg = "Could not read folder contents.";
Toast.MakeText(context, msg, ToastLength.Long).Show();
return;
}
var files = filter(dir.ListFiles(), onlyDirs, showHidden);
String[] names = Names(files);
ListAdapter = (new ArrayAdapter<String>(this, Resource.Layout.folder_chooser_item, names));
lv.ItemClick += (ff, gg) =>
{
var position = gg.Position;
if (!files[gg.Position].IsDirectory)
return;
String path = files[position].AbsolutePath;
var intent = new Intent(this, typeof(DirectoryPicker));
intent.PutExtra(DirectoryPicker.START_DIR, path);
intent.PutExtra(DirectoryPicker.SHOW_HIDDEN, showHidden);
intent.PutExtra(DirectoryPicker.ONLY_DIRS, onlyDirs);
StartActivityForResult(intent, PICK_DIRECTORY);
};
}
protected void OnActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_DIRECTORY && resultCode == (int)Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
returnDir(path);
}
}
private void returnDir(String path)
{
Intent result = new Intent();
result.PutExtra(CHOSEN_DIRECTORY, path);
SetResult(Result.Ok, result);
Finish();
}
public List<File> filter(File[] file_list, bool onlyDirs, bool showHidden)
{
var files = new List<File>();
foreach (var file in file_list)
{
if (onlyDirs && !file.IsDirectory)
continue;
if (!showHidden && file.IsHidden)
continue;
files.Add(file);
}
Collections.Sort(files);
return files;
}
public String[] Names(List<File> files)
{
String[] names = new String[files.Count];
int i = 0;
foreach (var file in files)
{
names[i] = file.Name;
i++;
}
return names;
}
}
}
Start activity as result then catch in OnActivityResult
if (requestCode == DirectoryPicker.PICK_DIRECTORY && resultCode == Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
// do stuff with path
}

How do I create an image of a webpage and save the image to my server using .net?

I have a page that dynamically generates a small html page containing 1 small table w/text. I want to be able to take a picture (png preferable) of that page and save it to my server.
I was previously using a 3rd party solution (ABCdrawHTML2), but I have changed servers and this one does not have it. Is there a way to do it without 3rd party solutions?
This is how I do it using the Windows.Forms WebBrowser:
public class WebSiteThumbnailImage
{
string m_Url;
int m_BrowserWidth, m_BrowserHeight, m_ThumbnailWidth, m_ThumbnailHeight;
Bitmap m_Bitmap = null;
public WebSiteThumbnailImage(string url, int browserWidth, int browserHeight, int thumbnailWidth, int thumbnailHeight)
{
m_Url = url;
m_BrowserWidth = browserWidth;
m_BrowserHeight = browserHeight;
m_ThumbnailWidth = thumbnailWidth;
m_ThumbnailHeight = thumbnailHeight;
}
public Bitmap GenerateWebSiteThumbnailImage()
{
Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
private void _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser = new WebBrowser();
m_WebBrowser.ScrollBarsEnabled = false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser = (WebBrowser)sender;
m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
}
}
To use this, at the appropriate place in your code-behind, do something like:
WebSiteThumbnailImage thumbnail = new WebSiteThumbnailImage(url, 1000, 1000, 200, 200);
Bitmap image = thumbnail.GenerateWebSiteThumbnailImage();
image.Save(filePath);

SharePoint Web Part Custom Properties Don't Take Effect Until Page Reload

I am developing a sharepoint 2007 web part that uses custom properties. Here is one:
[Personalizable(PersonalizationScope.User), WebDisplayName("Policy Update List Name")]
[WebDescription("The name of the SharePoint List that records all the policy updates.\n Default value is Policy Updates Record.")]
public string PolicyUpdateLogName
{
get { return _PolicyUpdateLogName == null ? "Policy Updates Record" : _PolicyUpdateLogName; }
set { _PolicyUpdateLogName = value; }
}
The properties work fine except that the changes are not reflected in the web part until you leave the page and navigate back (or just click on the home page link). Simply refreshing the page doesn't work, which makes me think it has something to do with PostBacks.
My current theory is that the ViewState is not loading postback data early enough for the changes to take effect. At the very least, the ViewState is involved somehow with the issue.
Thanks,
Michael
Here is more relevant code:
protected override void CreateChildControls()
{
InitGlobalVariables();
FetchPolicyUpdateLog_SPList();
// This function returns true if the settings are formatted correctly
if (CheckWebPartSettingsIntegrity())
{
InitListBoxControls();
InitLayoutTable();
this.Controls.Add(layoutTable);
LoadPoliciesListBox();
}
base.CreateChildControls();
}
...
protected void InitGlobalVariables()
{
this.Title = "Employee Activity Tracker for " + PolicyUpdateLogName;
policyColumnHeader = new Literal();
confirmedColumnHeader = new Literal();
pendingColumnHeader = new Literal();
employeesForPolicy = new List<SPUser>();
confirmedEmployees = new List<SPUser>();
pendingEmployees = new List<SPUser>();
}
...
// uses the PolicyUpdateLogName custom property to load that List from Sharepoint
private void FetchPolicyUpdateLog_SPList()
{
site = new SPSite(siteURL);
policyUpdateLog_SPList = site.OpenWeb().GetList("/Lists/" + PolicyUpdateLogName);
}
...
protected void InitListBoxControls()
{
// Init ListBoxes
policies_ListBox = new ListBox(); // This box stores the policies from the List we loaded from SharePoint
confirmedEmployees_ListBox = new ListBox();
pendingEmployees_ListBox = new ListBox();
// Postback & ViewState
policies_ListBox.AutoPostBack = true;
policies_ListBox.SelectedIndexChanged += new EventHandler(OnSelectedPolicyChanged);
confirmedEmployees_ListBox.EnableViewState = false;
pendingEmployees_ListBox.EnableViewState = false;
}
...
private void LoadPoliciesListBox()
{
foreach (SPListItem policyUpdate in policyUpdateLog_SPList.Items)
{
// Checking for duplicates before adding.
bool itemExists = false;
foreach (ListItem item in policies_ListBox.Items)
if (item.Text.Equals(policyUpdate.Title))
{
itemExists = true;
break;
}
if (!itemExists)
policies_ListBox.Items.Add(new ListItem(policyUpdate.Title));
}
}
Do some reading up on the Sharepoint web part life cycle. Properties are not updated until the OnPreRender event.

How to retrieve all key-value pairs in a resource file located in App_GlobalResources

In my ASP.NET MVC application, I manage localized texts in .resx files located in App_GlobalResources folder. I am able to retrieve any text value in any file knowing its key.
Now, I want to retrieve all key/value pairs in a particular resource file in order to write the result to some JavaScript. A search revealed that I might be able to use ResXResourceReader class and iterate through the pairs; however the class is unfortunately located in the System.Windows.Forms.dll and I don't want to wire that dependency to my web app. Is there any other way I can implement this feature?
I've found the solution. Now no need to reference Forms.dll.
public class ScriptController : BaseController
{
private static readonly ResourceSet ResourceSet =
Resources.Controllers.Script.ResourceManager.GetResourceSet(CurrentCulture, true, true);
public ActionResult GetResources()
{
var builder = new StringBuilder();
builder.Append("var LocalizedStrings = {");
foreach (DictionaryEntry entry in ResourceSet)
{
builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value);
}
builder.Append("};");
Response.ContentType = "application/x-javascript";
Response.ContentEncoding = Encoding.UTF8;
return Content(builder.ToString());
}
}
Okay, no other answer. Seems like referencing Forms.dll is the only way right now. Here's the code I came up with.
public class ScriptController : BaseController
{
private const string ResxPathTemplate = "~/App_GlobalResources/script{0}.resx";
public ActionResult GetResources()
{
var resxPath = Server.MapPath(string.Format(ResxPathTemplate, string.Empty));
var resxPathLocalized = Server.MapPath(string.Format(ResxPathTemplate,
"." + CurrentCulture));
var pathToUse = System.IO.File.Exists(resxPathLocalized)
? resxPathLocalized
: resxPath;
var builder = new StringBuilder();
using (var rsxr = new ResXResourceReader(pathToUse))
{
builder.Append("var resources = {");
foreach (DictionaryEntry entry in rsxr)
{
builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value);
}
builder.Append("};");
}
Response.ContentType = "application/x-javascript";
Response.ContentEncoding = Encoding.UTF8;
return Content(builder.ToString());
}
}

Resources