Showing posts with label telerik. Show all posts
Showing posts with label telerik. Show all posts

Tuesday, February 6, 2018

Issues using Telerik RadWindow and custom WindowManager in Caliburn Micro

Leave a Comment

I am currently working on a WPF project that utilizes Caliburn Micro and Caliburn.Micro.Telerik.

My issues are twofold. Firstly, if I create the View as a telerik:RadWindow then whenever the Show / ShowDialog method is called the window never gets displayed. If I create the view as UserControl then it will display.

Secondly TryClose() works fine without parameters but whenever I try and pass in true / false the window does not close.

For reference here are the pertinent pieces of code:

Window Manager Extensions:

public static class IWindowManagerExtensions {     /// <summary>     /// Opens an Alert modal window     /// </summary>     public static void Alert(this IWindowManager windowManager, string title, string message)     {         TelerikWindowManager.Alert(title, message);     }      /// <summary>     /// Opens an Alert modal window     /// </summary>     public static void Alert(this IWindowManager windowManager, DialogParameters dialogParameters)     {         TelerikWindowManager.Alert(dialogParameters);     }      /// <summary>     /// Opens a Confirm modal window     /// </summary>     public static void Confirm(this IWindowManager windowManager, string title, string message, System.Action onOK, System.Action onCancel = null)     {         TelerikWindowManager.Confirm(title, message, onOK, onCancel);     }      /// <summary>     /// Opens a Confirm modal window     /// </summary>     public static void Confirm(this IWindowManager windowManager, DialogParameters dialogParameters)     {         TelerikWindowManager.Confirm(dialogParameters);     }      /// <summary>     /// Opens a Prompt modal window     /// </summary>     public static void Prompt(this IWindowManager windowManager, string title, string message, string defaultPromptResultValue, Action<string> onOK)     {         TelerikWindowManager.Prompt(title, message, defaultPromptResultValue, onOK);     }      /// <summary>     /// Opens a Prompt modal window     /// </summary>     public static void Prompt(this IWindowManager windowManager, DialogParameters dialogParameters)     {         TelerikWindowManager.Prompt(dialogParameters);     } } 

Window Manager:

    public class TelerikWindowManager : WindowManager {     public override bool? ShowDialog(object rootModel, object context = null, IDictionary<string, object> settings = null)     {         var viewType = ViewLocator.LocateTypeForModelType(rootModel.GetType(), null, null);         if (typeof(RadWindow).IsAssignableFrom(viewType)             || typeof(UserControl).IsAssignableFrom(viewType))         {             var radWindow = CreateRadWindow(rootModel, true, context, settings);             radWindow.ShowDialog();             return radWindow.DialogResult;         }          return base.ShowDialog(rootModel, context, settings);     }      public override void ShowWindow(object rootModel, object context = null, IDictionary<string, object> settings = null)     {         var viewType = ViewLocator.LocateTypeForModelType(rootModel.GetType(), null, null);         if (typeof(RadWindow).IsAssignableFrom(viewType)             || typeof(UserControl).IsAssignableFrom(viewType))         {             NavigationWindow navWindow = null;              if (Application.Current != null && Application.Current.MainWindow != null)             {                 navWindow = Application.Current.MainWindow as NavigationWindow;             }              if (navWindow != null)             {                 var window = CreatePage(rootModel, context, settings);                 navWindow.Navigate(window);             }             else             {                 CreateRadWindow(rootModel, false, context, settings).Show();             }             return;         }         base.ShowWindow(rootModel, context, settings);     }       /// <summary>     /// Creates a window.     /// </summary>     /// <param name="rootModel">The view model.</param>     /// <param name="isDialog">Whethor or not the window is being shown as a dialog.</param>     /// <param name="context">The view context.</param>     /// <param name="settings">The optional popup settings.</param>     /// <returns>The window.</returns>     protected virtual RadWindow CreateRadWindow(object rootModel, bool isDialog, object context, IDictionary<string, object> settings)     {         var view = EnsureRadWindow(rootModel, ViewLocator.LocateForModel(rootModel, null, context), isDialog);         ViewModelBinder.Bind(rootModel, view, context);          var haveDisplayName = rootModel as IHaveDisplayName;         if (haveDisplayName != null && !ConventionManager.HasBinding(view, RadWindow.HeaderProperty))         {             var binding = new Binding("DisplayName") { Mode = BindingMode.TwoWay };             view.SetBinding(RadWindow.HeaderProperty, binding);         }          ApplyRadWindowSettings(view, settings);          new RadWindowConductor(rootModel, view);          return view;     }      bool ApplyRadWindowSettings(object target, IEnumerable<KeyValuePair<string, object>> settings)     {         if (settings != null)         {             var type = target.GetType();              foreach (var pair in settings)             {                 var propertyInfo = type.GetProperty(pair.Key);                  if (propertyInfo != null)                 {                     propertyInfo.SetValue(target, pair.Value, null);                 }             }              return true;         }          return false;     }      /// <summary>     /// Makes sure the view is a window is is wrapped by one.     /// </summary>     /// <param name="model">The view model.</param>     /// <param name="view">The view.</param>     /// <param name="isDialog">Whethor or not the window is being shown as a dialog.</param>     /// <returns>The window.</returns>     protected virtual RadWindow EnsureRadWindow(object model, object view, bool isDialog)     {         var window = view as RadWindow;          if (window == null)         {             var contentElement = view as FrameworkElement;             if (contentElement == null)                 throw new ArgumentNullException("view");              window = new RadWindow             {                 Content = view,                 SizeToContent = true,             };              AdjustWindowAndContentSize(window, contentElement);              window.SetValue(View.IsGeneratedProperty, true);              var owner = GetActiveWindow();             if (owner != null)             {                 window.WindowStartupLocation = WindowStartupLocation.CenterOwner;                 window.Owner = owner;             }             else             {                 window.WindowStartupLocation = WindowStartupLocation.CenterScreen;             }         }         else         {             var owner = GetActiveWindow();             if (owner != null && isDialog)             {                 window.Owner = owner;             }         }          return window;     }      /// <summary>     /// Initializes Window size with values extracted by the view.     ///      /// Note:     /// The real size of the content will be smaller than provided values.     /// The form has the header (title) and border so they will take place.     ///      /// </summary>     /// <param name="window">The RadWindow</param>     /// <param name="view">The view</param>     private static void AdjustWindowAndContentSize(RadWindow window, FrameworkElement view)     {         window.MinWidth = view.MinWidth;         window.MaxWidth = view.MaxWidth;         window.Width = view.Width;         window.MinHeight = view.MinHeight;         window.MaxHeight = view.MaxHeight;         window.Height = view.Height;          // Resetting view's settings         view.Width = view.Height = Double.NaN;         view.MinWidth = view.MinHeight = 0;         view.MaxWidth = view.MaxHeight = int.MaxValue;          // Stretching content to the Window         view.VerticalAlignment = VerticalAlignment.Stretch;         view.HorizontalAlignment = HorizontalAlignment.Stretch;     }      /// <summary>     /// Infers the owner of the window.     /// </summary>     /// <returns>The owner.</returns>     protected virtual Window GetActiveWindow()     {         if (Application.Current == null)         {             return null;         }          var active = Application.Current             .Windows.OfType<Window>()             .FirstOrDefault(x => x.IsActive);          return active ?? Application.Current.MainWindow;     }      public static void Alert(string title, string message)     {         RadWindow.Alert(new DialogParameters { Header = title, Content = message });     }      public static void Alert(DialogParameters dialogParameters)     {         RadWindow.Alert(dialogParameters);     }      public static void Confirm(string title, string message, System.Action onOK, System.Action onCancel = null)     {         var dialogParameters = new DialogParameters         {             Header = title,             Content = message         };         dialogParameters.Closed += (sender, args) =>         {             var result = args.DialogResult;             if (result.HasValue && result.Value)             {                 onOK();                 return;             }              if (onCancel != null)                 onCancel();         };         Confirm(dialogParameters);     }      public static void Confirm(DialogParameters dialogParameters)     {         RadWindow.Confirm(dialogParameters);     }      public static void Prompt(string title, string message, string defaultPromptResultValue, Action<string> onOK)     {         var dialogParameters = new DialogParameters         {             Header = title,             Content = message,             DefaultPromptResultValue = defaultPromptResultValue,         };         dialogParameters.Closed += (o, args) =>         {             if (args.DialogResult.HasValue && args.DialogResult.Value)                 onOK(args.PromptResult);         };          Prompt(dialogParameters);     }      public static void Prompt(DialogParameters dialogParameters)     {         RadWindow.Prompt(dialogParameters);     }  } 

Rad Window Conductor:

internal class RadWindowConductor {     private bool deactivatingFromView;     private bool deactivateFromViewModel;     private bool actuallyClosing;     private readonly RadWindow view;     private readonly object model;      public RadWindowConductor(object model, RadWindow view)     {         this.model = model;         this.view = view;          var activatable = model as IActivate;         if (activatable != null)         {             activatable.Activate();         }          var deactivatable = model as IDeactivate;         if (deactivatable != null)         {             view.Closed += Closed;             deactivatable.Deactivated += Deactivated;         }          var guard = model as IGuardClose;         if (guard != null)         {             view.PreviewClosed += PreviewClosed;         }     }      private void Closed(object sender, EventArgs e)     {         view.Closed -= Closed;         view.PreviewClosed -= PreviewClosed;          if (deactivateFromViewModel)         {             return;         }          var deactivatable = (IDeactivate)model;          deactivatingFromView = true;         deactivatable.Deactivate(true);         deactivatingFromView = false;     }      private void Deactivated(object sender, DeactivationEventArgs e)     {         if (!e.WasClosed)         {             return;         }          ((IDeactivate)model).Deactivated -= Deactivated;          if (deactivatingFromView)         {             return;         }          deactivateFromViewModel = true;         actuallyClosing = true;         view.Close();         actuallyClosing = false;         deactivateFromViewModel = false;     }      private void PreviewClosed(object sender, WindowPreviewClosedEventArgs e)     {         if (e.Cancel == true)         {             return;         }          var guard = (IGuardClose)model;          if (actuallyClosing)         {             actuallyClosing = false;             return;         }          bool runningAsync = false, shouldEnd = false;          guard.CanClose(canClose =>         {             Execute.OnUIThread(() =>             {                 if (runningAsync && canClose)                 {                     actuallyClosing = true;                     view.Close();                 }                 else                 {                     e.Cancel = !canClose;                 }                  shouldEnd = true;             });         });          if (shouldEnd)         {             return;         }          e.Cancel = true;         runningAsync = true;     } } 

New User View Model:

    [Export, PartCreationPolicy(CreationPolicy.NonShared)] [ExportController("NewUserViewModel")] public class NewUserViewModel : FeatureWindowBase {     #region Fields     private User _creatingUser;     private User _userToAdd;     #endregion      #region Properties      public bool IsOpen;      public User UserToAdd     {         get         {             return _userToAdd;          }         set         {             _userToAdd = value;              NotifyOfPropertyChange(() => UserToAdd);         }     }      public IEnumerable<Entity> AddedUsers => new List<Entity>() { UserToAdd };      #endregion       #region Constructors      [ImportingConstructor]     public NewUserViewModel(IWindowManager windowManager,         IEventAggregator eventAggregator,         IEntityManagerProvider<BearPawEntities> entityManagerProvider,         IGlobalCache globalCache) :         base(windowManager, eventAggregator, entityManagerProvider, globalCache)     {     }      #endregion      protected override void OnViewLoaded(object view)     {         base.OnViewLoaded(view);          // un-comment the following if you want to use the Global Cache         SetupGlobalCache<User>(Manager);         _creatingUser = Manager.Users.FirstOrDefault(u => u.UserName ==                                                  Manager.AuthenticationContext.Principal.Identity                                                      .Name);          UserToAdd = new User()         {             CreatedBy = _creatingUser,             CreatedDate = DateTime.Now,             ModifiedBy = _creatingUser,             ModifiedDate = DateTime.Now         };          DisplayName = "Add New User";         IsOpen = true;     }      #region Methods       public async Task CreateUser()     {         try         {              var newAuth = new UserAuthentication()             {                 Password = Security.CreateSaltedPasswordForNewUser("LetMeIn"),                 Salt = Security.LastSalt,                 CreatedBy = _creatingUser,                 CreatedDate = DateTime.Now,                 ModifiedBy = _creatingUser,                 ModifiedDate = DateTime.Now             };               Security.ClearLastSalt();              Manager.AddEntity(newAuth);             UserToAdd.UserAuthentication = newAuth;              Manager.AddEntity(UserToAdd);              var saveResponse = await Manager.TrySaveChangesAsync();              if (saveResponse.Ok)             {                 TryClose(true);             }         }         catch (Exception)         {             throw;         }     }      #endregion  } 

Finally, from our App Bootstrapper:

        protected override void Configure()     {         IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("xunit.*");         IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("BearPaw.Client.*");         IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("BearPaw.Clients.*");         IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("Caliburn.*");         IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("JetBrains.*");         IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("FluentAssertions.*");          var conventions = new RegistrationBuilder();         conventions.ForTypesDerivedFrom<IBearPawFeature>()             .Export()             .SetCreationPolicy(CreationPolicy.NonShared);           _container = new CompositionContainer(             new AggregateCatalog(                 AssemblySource.Instance.Select(x=> new AssemblyCatalog(x, conventions)).OfType<ComposablePartCatalog>()                 )             );          var batch = new CompositionBatch();          batch.AddExportedValue<IWindowManager>(new TelerikWindowManager());         batch.AddExportedValue<IEventAggregator>(new EventAggregator());         batch.AddExportedValue<IEntityManagerProvider<BearPawEntities>>(new MainEntityManagerProvider());         batch.AddExportedValue<IEntityManagerProvider<BearPawReportingEntities>>(new ReportingEntityManagerProvider());         batch.AddExportedValue(_container);          // This is essential to enable Telerik's conventions         TelerikConventions.Install();          AddKeyBindingTriggers();          VisualStudio2013Palette.LoadPreset(VisualStudio2013Palette.ColorVariation.Dark);         VisualStudio2013Palette.Palette.BasicColor = Color.FromArgb(255, 77, 77, 82);           _container.Compose(batch);     } 

If anyone has any ideas on what may be up I would be super grateful.

Thanks in advance

0 Answers

Read More

Thursday, April 6, 2017

Accent insensitive searching in RadComboBox

Leave a Comment

I'm relatively new to using ASP webforms and Telerik, but I'm looking for a way that allows me to type special characters (é, ù, à, ...) in a RadComboBox.

Lets say I have a name in my ObjectDataSource called "René Somebody". I need to be able to find him by searching for "Rene" and "René", but so far no luck.

In the application they managed to do this on a RadGrid with filters, but this same solution doesn't work for the RadComboBox as far as I know.

The solution they used in the RadGrid: http://www.telerik.com/forums/accent-insensitive-filtering-filtering-on-a-different-column#YS1QT8P1U0-cRPFNfjvDzA

1 Answers

Answers 1

I have no access to the backend components but the demo you linked contains frontend code and it looks like you can hack in there. It looks like this control may be both client-server and client-side only. For client-side only hacks looks kind of complicated and invloves non-public API (_onInputChange) but for client-server case (which is probably your case) the doc on client side of RadComboBox Object mentions requestItems method so hacking it is probably reasonably future safe:

var hackRadComboBoxFilter = function (combobox, filterProcessingFunction) {     var oldRequestItems = combobox.requestItems;      combobox.requestItems = function() {         var args = Array.prototype.slice.call(arguments);         // requestItems has several arguments but the text seems to be the         // first one, so let's modify it and call the original method         var origFilter = args[0];         args[0] = filterProcessingFunction(origFilter);         oldRequestItems.apply(this, args);     } }; 

Unfortunately I don't know a built-in way to deal with accents in JS but you can hack something simple here as well:

var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž'; var mappedAccents = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz"; var removeAccents = function (origStr) {     var components = [];     var len = origStr.length;     var afterLastAccent = 0;     for (var i = 0; i < len; i++) {         var mapPos = accents.indexOf(origStr[i]);         if (mapPos != -1) {             components.push(origStr.substr(afterLastAccent, i - afterLastAccent) + mappedAccents[mapPos]);             afterLastAccent = i + 1;         }     }     if (afterLastAccent < len)         components.push(origStr.substr(afterLastAccent, len - afterLastAccent));     return components.join(''); }; 

So now you can combine it in something like this:

// In real app you probably want something like this // var targetComboBox = $find("<%= RadComboBox1.ClientID %>"); // but for test let's just hack first combobox on the page var targetComboBox = Telerik.Web.UI.RadComboBox.ComboBoxes[0]; hackRadComboBoxFilter(targetComboBox, removeAccents); 

or if you want to modify all the comboboxes on the page, you can change prototype using the same trick:

hackRadComboBoxFilter(Telerik.Web.UI.RadComboBox.prototype, removeAccents) 
Read More

Thursday, March 30, 2017

GridGroupHeaderItem.AggregatesValues without Eval

Leave a Comment

In telerik documentation, It's say that aggregates values are store in the AggregatesValues. They even use it in the exemple.

But I find it impossible to prove. As everying is true until proven wrong .. right?
Let me provide you a Minimal, Complete, and Verifiable example. So you could point my mistake.

Aspx :

<telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource" AllowPaging="True" ShowGroupPanel="True">     <MasterTableView>         <GroupByExpressions>             <telerik:GridGroupByExpression>                 <SelectFields>                                            <telerik:GridGroupByField FieldAlias="GrpGroupID1" FieldName="GroupID" />                     <telerik:GridGroupByField FieldAlias="SumCount" FieldName="Count" Aggregate="Sum" />                 </SelectFields>                 <GroupByFields>                     <telerik:GridGroupByField FieldAlias="GrpGroupID" FieldName="GroupID" HeaderText="" />                 </GroupByFields>             </telerik:GridGroupByExpression>         </GroupByExpressions>         <GroupHeaderTemplate>             <table>                 <tr>                     <td>eval GrpGroupID1:</td>                     <td><%# Eval("GrpGroupID1") %></td>                     <td> ||| </td>                     <td>Bind GrpGroupID1:</td>                     <td><%# ((GridGroupHeaderItem)Container).AggregatesValues["GrpGroupID1"] %></td>                 </tr>                 <tr>                     <td>eval SumCount:</td>                     <td><%# Eval("SumCount") %></td>                     <td> ||| </td>                     <td>Bind SumCount:</td>                     <td><%# ((GridGroupHeaderItem)Container).AggregatesValues["SumCount"] %></td>                 </tr>             </table>         </GroupHeaderTemplate>         <Columns>             <telerik:GridNumericColumn DataField="ID" HeaderText="ID" SortExpression="ID" UniqueName="Name_ID" />             <telerik:GridNumericColumn DataField="GroupID" HeaderText="GroupID" SortExpression="GroupID" UniqueName="Name_GroupID" />             <telerik:GridBoundColumn DataField="Name" HeaderText="Name" SortExpression="Name" UniqueName="Name_Name" />             <telerik:GridBoundColumn DataField="Text" HeaderText="Text" SortExpression="Text" UniqueName="Name_Text" />                             <telerik:GridNumericColumn DataField="Count" HeaderText="Count" SortExpression="Count" UniqueName="Name_Count" Aggregate="Sum" />         </Columns>     </MasterTableView>  </telerik:RadGrid> 

Code behind :

protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e) {     List<TmpType> myData = new List<TmpType>();      List<string> firstNames = new List<string>() { "Angela", "Pamela", "Sandra", "Rita", "Monica", "Erica", "Tina", "Mary", "Jessica", "Loubega" };     List<string> Location = new List<string>() { "Reunion", "Paris", "Bretagne", "Madagascar", "UK", "Maurice" };     Random random = new Random();      for (int i = 0; i <= 88; i++)     {         TmpType row = new TmpType();         row.ID = i + 1;         row.GroupID = random.Next(10);         row.Count = random.Next(10);         row.Name = firstNames[random.Next(firstNames.Count)];         row.Text = Location[random.Next(Location.Count)];         myData.Add(row);     }     RadGrid1.DataSource = myData; }  class TmpType {     public string Name { get; set; }     public string Text { get; set; }     public int Count { get; set; }     public int GroupID { get; set; }     public int ID { get; set; } } 

Result :

Key and values of AggregatesValues in debug:

Key and values of AggregatesValues in debug

Exemple of data display: Exemple of data display

As you can see in this exemple:
- Eval("SumCount") can find the value
when :
- ((GridGroupHeaderItem)Container).AggregatesValues["SumCount"] fail !

The documentation says:

the field alias name when you want to access the total aggregate of the items in the current group.

And SumCount is my FieldAlias.

What I try:

Here is a list of every thing i have try and the result.

Eval() : always almost correct, the approximate knowledge of nearly everything.

  1. Eval("GrpGroupID1"), Give the current value of the groupby field, OK!
  2. Eval("SumCount"), Give the correct result of the aggregate function, OK!
  3. Eval("Count"), Give the value of the row for this group (4), not Expected.
  4. Eval("Name_Count"), Error because this is not a properties of anything, OK!

AggregatesValues: It will be fast !

  1. ((GridGroupHeaderItem)Container).AggregatesValues["GrpGroupID1"], Give the current value of the groupby field, OK!

  2. Everything else, Return NULL

Those test have been made using a asp:Label and not using an Label.

Side note:

  • Yes, I could simply use the Eval. But why? Why would I use an Eval when MSDN state that I should not use it and when the Telerik documentation state that I can use the aggregates values collection.

Where is the question?

Many will be asking: "Where is the question?".
How can I get this GridGroupHeaderItem.AggregatesValues without Eval or Bind ?

0 Answers

Read More

Friday, February 10, 2017

JQuery exceptions using Internet Explorer 11 & ASP .NET

Leave a Comment

When I'm navigating through my ASP .NET site I'm getting the following JQuery exceptions while using Internet Explorer. Also, I'm using Telerik Controls suite for ASP .NET & Visual Studio 2012.

enter image description here

If I check for the line numbers in ScriptResource.axd?d=... (Telerik's file):

/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */  a.querySelectorAll("*,:x"), //Line 10673  s.call(a,"[s!='']:x"), //Line 10898 

And in my jquery-2.1.0.min.js:

/*! jQuery v2.1.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */  a.querySelectorAll("*,:x") //Line 10357  q.call(a,"[s!='']:x") //Line 10571 

In both files I'm getting an exception in the same two sentences. Those exceptions are not causing extrange behaviour but I don't like to see them in Visual Studio as there might be a signal that something is wrong.

NOTE: If i remove Telerik's JQuery or Standard JQuery the error still there. Even if i set the Telerik's JQuery to use the standar one the error still there. Also, NO errors in console.

What's happening?

3 Answers

Answers 1

Short answer:

There is nothing wrong with jquery - sometimes it do its own 'dirty' business to make your hands clean since sometimes there is no 'clean' way to do what needs to be done

TLDR;

Long answer:

It seems like in both cases you saw caught errors from jQuery, since, according to Telerik documentation, some Telerik controls depends on jQuery - so you would have jQuery out of box

About exceptions - after jQuery loads, its do a feature detection - as you know, browser behavior vary for each browser/version and often there is no way to do detection without trying using features and catching exceptions if the feature is not supported

For example the first exception (at a.querySelectorAll("*,:x")) happens when jquery do a feature detection for selectors supported by document.querySelectorAll - you can simply find it in by searching at github or in any non minified jquery file:

// Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); 

As you can see its intended behavior and there is no way to avoid it as long as you have jquery on your page

Answers 2

The jQuery team uses exceptions in certain situations for logic flow. They uses the assert function to do feature detection for each browser. If you look into the jQuery code, you could find the assert function like the following

function assert( fn ) {     var el = document.createElement("fieldset");      try {         return !!fn( el );     } catch (e) {         return false;     } finally {         // Remove from its parent by default         if ( el.parentNode ) {             el.parentNode.removeChild( el );         }         // release memory in IE         el = null;     } } 

To desmontrate, I've created a sample asp.net webpage that using jQuery 3.1.1. When I run the webpage locally, selecting Internet Explorer and run it within Visual Studio, it will raise the exceptions like this

... 'iexplore.exe' (Script): Loaded 'Script Code (Windows Internet Explorer)'.  Exception was thrown at line 1361, column 4 in http://localhost:63177/Scripts/jquery-3.1.1.js 0x800a139e - JavaScript 実行時エラー: SyntaxError Exception was thrown at line 1379, column 4 in http://localhost:63177/Scripts/jquery-3.1.1.js 0x800a139e - JavaScript 実行時エラー: SyntaxError Exception was thrown at line 37, column 60610 in http://localhost:63409/15db952270ca47e19969bb659e432c6d/browserLink 0x800a139e - JavaScript 実行時エラー: SyntaxError The thread 0x5250 has exited with code 0 (0x0). ... 

Looking at lines 1361 and 1379 in jQuery 3.1.1 code, you will find these error was raised on purpose.

Line 1360-1361

// Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); 

Line 1377-1379

// This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); 

Since the exception was handled, the jQuery team don't consider it a problem. You could refer the similar problem as the following link https://bugs.jquery.com/ticket/14123

It's intended codes of jQuery, so I think you could leave it as it is.

Answers 3

If this issue only occurs when debugging a web site/page in the Visual Studio, try disabling the Visual Studio -> Browser Link option either using a corresponding toolbar item or by adding the following key to the Web.config:

<appSettings>     <add key="vs:EnableBrowserLink" value="false"/> </appSettings> 

Refer to the following threads to learn more about different known Browser Link effects (similar to yours), related to the aforementioned JavaScript errors:

VS 2013 Browser Link generated script causes jQuery reference to be broken when using RequireJS

Page uses an invalid or unsupported form of compression when debugging ASP.NET MVC app with Visual Studio 2013 Preview

Browser Link feature in Visual Studio Preview 2013

Read More

Wednesday, June 22, 2016

How to show more that one image in the radtreeview item (wpf - telerik )

Leave a Comment

I am adding image to the radtreeviewitem from resources programatically using the below code.

"/myAssembley;component/Resources/image1.png" 

and the image is displaying successfully. Now i need to add another image which needs to be displayed next to the first image in the radtreeviewitem.

how to achieve it.?

Like the below image i need my treeviewitem to display a folder icon and a red square icon in a single treeview item.

enter image description here

2 Answers

Answers 1

If you do not have data binding and you are using RadTreeViewItems directly you can add the additional image in the Header of the item. For example:

var stackPanel = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Horizontal }; var image1 = new Image() { Source = image1Path }; var image2 = new Image() { Source = image2Path }; var textBlock = new TextBlock() { Text = itemHeader }; stackPanel.Children.Add(image1); stackPanel.Children.Add(image2); stackPanel.Children.Add(textBlock);  var treeViewItem = new RadTreeViewItem() {     Header = stackPanel, }; 

It Works.

Answers 2

The proper way would be to create a DataTemplate with a grid or horizontal stackpanel. Put two images inside and in your model two Image Sources that you can bind too. Telerik doesn't have the best track record using the MVVM pattern, but the TreeView control is pretty decent with binding. If you need help with the model and the datatemplate, post some of your code here and we can work on it.

Read More

Friday, April 29, 2016

Scroll viewer resize (Right bottom corner ) in wpf

Leave a Comment

I have scroll viewer enabled in treeview and listbox and have even customized the scroll bars refering this site and i have acheived what i need .My scroll bar is now looking like below

enter image description here

but i need my scrollbar to be look like this

enter image description here

I need that space in right bottom corner to be filled with horizontal or vertical scroll bar .Is it possible in wpf ??

Below is the customized style for the scrollbar

<local:ThicknessConverter x:Key="ThicknessConverter" />     <Style x:Key="{x:Type ScrollBar}" TargetType="{x:Type ScrollBar}">         <Setter Property="SnapsToDevicePixels" Value="True"/>         <Setter Property="OverridesDefaultStyle" Value="true"/>         <Style.Triggers>             <Trigger Property="Orientation" Value="Horizontal">                 <Setter Property="Width" Value="Auto"/>                 <Setter Property="Height" Value="18" />                 <Setter Property="Template"                      Value="{StaticResource HorizontalScrollBar}" />             </Trigger>             <Trigger Property="Orientation" Value="Vertical">                 <Setter Property="Width" Value="18"/>                 <Setter Property="Height" Value="Auto" />                 <Setter Property="Template"                      Value="{StaticResource VerticalScrollBar}" />             </Trigger>             <Trigger Property="Name" Value="PART_VerticalScrollBar">                 <Setter Property="Margin" Value="{Binding RelativeSource={RelativeSource AncestorType=ScrollViewer},Converter={StaticResource ThicknessConverter}}">                 </Setter>             </Trigger>          </Style.Triggers>       </Style> 

and here is there treeview code

   <telerik:RadTreeView x:Name="radTreeView"   Background="#4E4E4E" Margin="0,0,456,0" Grid.Row="2"                 ItemsSource="{x:Static local:MainWindow.AnimalCategories}" ItemPrepared="treeView_ItemPrepared"                               ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" Grid.RowSpan="2" Grid.ColumnSpan="2">             <telerik:RadTreeView.ItemTemplate>                 <HierarchicalDataTemplate ItemsSource="{Binding Animals}">                     <TextBlock  Text="{Binding Category}" />                     <HierarchicalDataTemplate.ItemTemplate>                         <DataTemplate>                              <TextBlock Text="{Binding Name}"/>                          </DataTemplate>                     </HierarchicalDataTemplate.ItemTemplate>                 </HierarchicalDataTemplate>             </telerik:RadTreeView.ItemTemplate>          </telerik:RadTreeView> 

1 Answers

Answers 1

Below is a way to do it:

XAML:

 <ScrollViewer Height="400" Width="400" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" >     <ScrollViewer.Resources>         <local:ThicknessConverter x:Key="ThicknessConverter" />         <Style TargetType="ScrollBar">             <Style.Triggers>                 <Trigger Property="Orientation" Value="Horizontal">                     <Setter Property="Margin" Value="{Binding RelativeSource={RelativeSource AncestorType=ScrollViewer},Converter={StaticResource ThicknessConverter}}">                     </Setter>                 </Trigger>             </Style.Triggers>         </Style>     </ScrollViewer.Resources> </ScrollViewer> 

Converter:

public class ThicknessConverter : IValueConverter {     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)     {         var scrollBars = FindVisualChildren<ScrollBar>(value as DependencyObject);         foreach (var scrollBar in scrollBars)         {             if (scrollBar.Orientation == Orientation.Horizontal)             {               return  new Thickness(0, 0, 0, 0 - scrollBar.ActualHeight);             }         }         return new Thickness(0, 0, 0, 0);     }      public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject     {         if (depObj != null)         {             for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)             {                 DependencyObject child = VisualTreeHelper.GetChild(depObj, i);                 if (child != null && child is T)                 {                     yield return (T)child;                 }                  foreach (T childOfChild in FindVisualChildren<T>(child))                 {                     yield return childOfChild;                 }             }         }     }              public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)     {         throw new NotImplementedException();     } } 

OUTPUT:

Scroll

Read More

Wednesday, March 23, 2016

Registering Push IOS Notification with Telerik Appbuilder

1 comment

I have registered my Telerik Appbuilder (cordova) app for Push Notifications. Everything works fine, except for the fact that when the user is inside the application, he does not receive the push notification.

It works fine as long as he is on the 1 page that registers his push ie:

var registerPush = function (user, callback) {     $(".modal-loader").show();     document.addEventListener("deviceready", function () {         var el = new Everlive('m4yh8cw6ei7xxwio');          var pushSettings = {             iOS: {                 badge: true,                 sound: true,                 alert: true,                 clearBadge: true             },             notificationCallbackIOS: function (e) {                              navigator.notification.alert(e.alert, function () { }, "Alert", "Ok");             },             customParameters: {                 login: user             }          };          el.push.register(             pushSettings,             function () {                 $(".modal-loader").hide();                 callback();             }             ,             function errorCallback(error) {                 // This callback will be called any errors occurred during the device                 // registration process                 console.log("error registering push");                 console.log(data);             }         );     }, false); } 

If the user is on the page that actually registers this function, then he will be alerted via the navigationCallbackIOS. but as soon as we browse to a different page via:

 location.href= nextpage.html  

then the navigationCallbackIOS no longer works. What is the logic I need to implement here to have a global callback that works on every page?

2 Answers

Answers 1

If you change the page like this location.href= nextpage.html, then it's a different page, the webview is reloaded and all the code you executed on the index.html won't exist anymore.

You have two options.

  1. Switch to SPA, where you only have the index.html and you load just the contents of the nextpage.html, but don't navigate to it using the location.href
  2. Execute all the code on every .html file. If you have a pushHandler.js (example) where you init the push and register the listeners, link it on any .html so it is executed again when you change the page.

Answers 2

An AJAX request instead of a location.href change would be really better for three motivations: 1. Speed 2. No reload (don't need to reload every single resource everytime) 3. Global scope - in your case the push notification registration, don't need to be re-run every page change.

To do so you could create a element and then load into it the content of the other pages.. Take a look here for some proof of concept. It's basically all around managing an XMLHttpRequest and putting the result into a DOM element.

Read More