c#,angularjs,umbraco7 , Umbraco 7 load content media picker in custom section


Umbraco 7 load content media picker in custom section

Question:

Tag: c#,angularjs,umbraco7

I've created a custom section in Umbraco 7 that references external urls, but have a requirement to extend it to use exactly the same functionality as the media picker from the 'Content' rich text editor. I don't need any other rich text functionality other than to load the media picker overlay from an icon, and select either an internal or external url.

I've tried to distil the umbraco source code, as well as trying various adaptations of online tutorials, but as yet I can't get the media picker to load.

I know that fundamentally I need:

However, as yet I haven't been able to wire it all together, so any help much appreciated.


Answer:

So, this is how I came up with the solution.....

The first win was that I discovered 2 excellent tutorial blog posts, upon the shoulders of which this solution stands, so much respect to the following code cats:

Tim Geyssons - Nibble postings: http://www.nibble.be/?p=440

Markus Johansson - Enkelmedia http://www.enkelmedia.se/blogg/2013/11/22/creating-custom-sections-in-umbraco-7-part-1.aspx

  1. Create a model object to represent a keyphrase, which will be associated to a new, simple, ORM table. The ToString() method allows a friendly name to be output on the front-end.

     [TableName("Keyphrase")]
     public class Keyphrase
     {
        [PrimaryKeyColumn(AutoIncrement = true)]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Phrase { get; set; }
        public string Link { get; set; }
    
        public override string ToString()
        {
            return Name;
        }
    }
    
  2. Create an Umbraco 'application' that will register the new custom section by implementing the IApplication interface. I've called mine 'Utilities' and associated it to the utilities icon.

    [Application("Utilities", "Utilities", "icon-utilities", 8)]
    public class UtilitiesApplication : IApplication { }
    

The decorator allows us to supply a name, alias, icon and sort-order of the new custom section.

  1. Create an Umbraco tree web controller that will allow us to create the desired menu behaviour for our keyphrases, and display the keyphrase collection from our database keyphrase table.

    [PluginController("Utilities")]
    [Umbraco.Web.Trees.Tree("Utilities", "KeyphraseTree", "Keyphrase", iconClosed: "icon-doc", sortOrder: 1)]
    public class KeyphraseTreeController : TreeController
    {
        private KeyphraseApiController _keyphraseApiController;
    
        public KeyphraseTreeController()
        {
             _keyphraseApiController = new KeyphraseApiController();
        }
    
        protected override TreeNodeCollection GetTreeNodes(string id,                                                                FormDataCollection queryStrings)
        {
            var nodes = new TreeNodeCollection();
            var keyphrases = _keyphraseApiController.GetAll();
    
            if (id == Constants.System.Root.ToInvariantString())
            {
                foreach (var keyphrase in keyphrases)
                {
                    var node = CreateTreeNode(
                    keyphrase.Id.ToString(),
                    "-1",
                    queryStrings,
                    keyphrase.ToString(),
                    "icon-book-alt",
                    false);
    
                    nodes.Add(node);
                }
            }
    
            return nodes;
        }
    
        protected override MenuItemCollection GetMenuForNode(string id,                                                               FormDataCollection queryStrings)
        {
            var menu = new MenuItemCollection();
    
            if (id == Constants.System.Root.ToInvariantString())
            {
                // root actions
                 menu.Items.Add<CreateChildEntity, ActionNew>(ui.Text("actions", ActionNew.Instance.Alias));
                menu.Items.Add<RefreshNode, ActionRefresh>(ui.Text("actions", ActionRefresh.Instance.Alias), true);
                return menu;
            }
            else
            {
                menu.Items.Add<ActionDelete>(ui.Text("actions", ActionDelete.Instance.Alias));
            }
            return menu;
        }
    }
    

The class decorators and TreeController extension allow us to declare the web controller for our keyphrase tree, associate it to our Utilities custom section, as well as choose an icon and sort order.

We also declare an api controller (we'll get to that!), which will allow us access to our Keyphrase data object.

The GetTreeNodes method allows us to iterate the keyphrase data collection and return the resultant nodes to the view.

The GetMenuNode method allows us to create the menu options we require for our custom section. We state that if the node is the root (Utilities), then allow us to add child nodes and refresh the node collection. However, if we are lower in the node tree (Keyphrase) then we only want users to be able to delete the node (ie the user shouldn't be allowed to create another level of nodes deeper than Keyphrase)

  1. Create an api controller for our Keyphrase CRUD requests

    public class KeyphraseApiController : UmbracoAuthorizedJsonController
    {
        public IEnumerable<Keyphrase> GetAll()
        {
            var query = new Sql().Select("*").From("keyphrase");
            return DatabaseContext.Database.Fetch<Keyphrase>(query);
        }
    
        public Keyphrase GetById(int id)
        {
            var query = new Sql().Select("*").From("keyphrase").Where<Keyphrase>(x => x.Id == id);
            return DatabaseContext.Database.Fetch<Keyphrase>(query).FirstOrDefault();
        }
    
        public Keyphrase PostSave(Keyphrase keyphrase)
        {
            if (keyphrase.Id > 0)
                DatabaseContext.Database.Update(keyphrase);
            else
                DatabaseContext.Database.Save(keyphrase);
    
            return keyphrase;
        }
    
        public int DeleteById(int id)
        {
            return DatabaseContext.Database.Delete<Keyphrase>(id);
        }
    }
    
  2. Create the custom section views with angular controllers, which is the current architectual style in Umbraco 7. It should be noted that Umbraco expects that your custom section components are put into the following structure App_Plugins//BackOffice/

We need a view to display and edit our keyphrase name, target phrase and url

    <form name="keyphraseForm"
        ng-controller="Keyphrase.KeyphraseEditController"
        ng-show="loaded"
        ng-submit="save(keyphrase)"
        val-form-manager>
            <umb-panel>
                <umb-header>
                    <div class="span7">
                        <umb-content-name placeholder=""
                                          ng-model="keyphrase.Name" />
                    </div>

                    <div class="span5">
                        <div class="btn-toolbar pull-right umb-btn-toolbar">
                            <umb-options-menu ng-show="currentNode"
                                              current-node="currentNode"
                                              current-section="{{currentSection}}">
                            </umb-options-menu>
                        </div>
                    </div>
                </umb-header>

                <div class="umb-panel-body umb-scrollable row-fluid">
                    <div class="tab-content form-horizontal" style="padding-bottom: 90px">
                        <div class="umb-pane">
                            <umb-control-group label="Target keyphrase"                                                   description="Keyphrase to be linked'">
                                <input type="text" class="umb-editor umb-textstring" ng-model="keyphrase.Phrase" required />
                            </umb-control-group>

                            <umb-control-group label="Keyphrase link" description="Internal or external url">
                                <p>{{keyphrase.Link}}</p>
                                <umb-link-picker ng-model="keyphrase.Link" required/>
                            </umb-control-group>

                            <div class="umb-tab-buttons" detect-fold>
                                <div class="btn-group">
                                    <button type="submit" data-hotkey="ctrl+s" class="btn btn-success">
                                        <localize key="buttons_save">Save</localize>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </umb-panel>
        </form>

This utilises umbraco and angular markup to display data input fields dynamically and associate our view to an angular controller that interacts with our data layer

    angular.module("umbraco").controller("Keyphrase.KeyphraseEditController",
    function ($scope, $routeParams, keyphraseResource, notificationsService, navigationService) {

        $scope.loaded = false;

        if ($routeParams.id == -1) {
            $scope.keyphrase = {};
            $scope.loaded = true;
        }
        else {
            //get a keyphrase id -> service
            keyphraseResource.getById($routeParams.id).then(function (response) {
            $scope.keyphrase = response.data;
            $scope.loaded = true;
        });
    }

    $scope.save = function (keyphrase) {
        keyphraseResource.save(keyphrase).then(function (response) {
            $scope.keyphrase = response.data;
            $scope.keyphraseForm.$dirty = false;
            navigationService.syncTree({ tree: 'KeyphraseTree', path: [-1, -1], forceReload: true });
            notificationsService.success("Success", keyphrase.Name + " has been saved");
        });
    };

});

Then we need html and corresponding angular controller for the keyphrase delete behaviour

    <div class="umb-pane" ng-controller="Keyphrase.KeyphraseDeleteController">
        <p>
            Are you sure you want to delete {{currentNode.name}} ?
        </p>
        <div>
            <div class="umb-pane btn-toolbar umb-btn-toolbar">
                <div class="control-group umb-control-group">
                    <a href="" class="btn btn-link" ng-click="cancelDelete()"
                        <localize key="general_cancel">Cancel</localize>
                    </a>
                    <a href="" class="btn btn-primary" ng-click="delete(currentNode.id)">
                        <localize key="general_ok">OK</localize>
                    </a>
                </div>
            </div>
        </div>
    </div>
  1. Utilise Umbraco's linkpicker to allow a user to select an internal or external url. We need html markup to launch the LinkPicker

    <div>
        <ul class="unstyled list-icons">
            <li>
                <i class="icon icon-add blue"></i>
                <a href ng-click="openLinkPicker()" prevent-default>Select</a>
            </li>
        </ul>
    </div>
    

And an associated directive js file that launches the link picker and posts the selected url back to the html view

    angular.module("umbraco.directives")
        .directive('umbLinkPicker', function (dialogService, entityResource)         {
            return {
                restrict: 'E',
                replace: true,
                templateUrl: '/App_Plugins/Utilities/umb-link-picker.html',
                require: "ngModel",
                link: function (scope, element, attr, ctrl) {

                    ctrl.$render = function () {
                        var val = parseInt(ctrl.$viewValue);

                        if (!isNaN(val) && angular.isNumber(val) && val > 0) {

                            entityResource.getById(val, "Content").then(function (item) {
                                scope.node = item;
                            });
                        }
                };

                scope.openLinkPicker = function () {
                    dialogService.linkPicker({ callback: populateLink });
                }

                scope.removeLink = function () {
                    scope.node = undefined;
                    updateModel(0);
                }

                function populateLink(item) {
                    scope.node = item;
                    updateModel(item.url);

                }

                function updateModel(id) {
                    ctrl.$setViewValue(id);

                }
            }
        };
    });

There is one final js file that allows us to send data across the wire, with everyone's favourite http verbs GET, POST(handles put too here too) and DELETE

    angular.module("umbraco.resources")
        .factory("keyphraseResource", function ($http) {
            return {
                getById: function (id) {
                    return $http.get("BackOffice/Api/KeyphraseApi/GetById?id=" + id);
                },
                save: function (keyphrase) {
                    return $http.post("BackOffice/Api/KeyphraseApi/PostSave", angular.toJson(keyphrase));
                },
                deleteById: function (id) {
                    return $http.delete("BackOffice/Api/KeyphraseApi/DeleteById?id=" + id);
                }
            };
        });

In addition, we will need a package manifest to register our javascript behaviour

    {
        javascript: [
        '~/App_Plugins/Utilities/BackOffice/KeyphraseTree/edit.controller.js',
            '~/App_Plugins/Utilities/BackOffice/KeyphraseTree/delete.controller.js',
        '~/App_Plugins/Utilities/keyphrase.resource.js',
        '~/App_Plugins/Utilities/umbLinkPicker.directive.js'
        ]
    }
  1. Implement tweaks to allow the CMS portion of the solution to work correctly. At this point we've almost got our custom section singing, but we just need to jump a couple more Umbraco hoops, namely a) add a keyphrase event class that creates our keyphrase db table if it doesn't exist (see point 8) b) fire up Umbraco and associate the new custom section to the target user (from the User menu) c) alter the placeholder text for the custom section by searching for it in umbraco-->config-->en.xml and swapping out the placeholder text for 'Utilities'

  2. Intercept target content fields of target datatypes when content is saved or published The requirement I was given was to intercept the body content of a news article, so you'll need to create a document type in Umbraco that has, for example, a title field of type 'Textstring', and bodyContent field of type 'Richtext editor'.

You'll also want a, or many, keyphrase(s) to target, which should now be in a new Umbraco custom section, 'Utilities'

Here I've targeted the keyphrase 'technology news' to link to the bbc technology news site so that any time I write the phrase 'technology news' the href link will be inserted automatically. This is obviously quite a simple example, but would be quite powerful if a user needed to link to certain repetitive legal documents, for example tax, property, due dilligence, for example, which could be hosted either externally or within the CMS itself. The href link will open an external resource in a new tab, and internal resource in the same window (we'll get to that in Point 9)

So, the principle of what we're trying to achieve is to intercept the Umbraco save event for a document and manipulate our rich text to insert our link. This is done as follows: a) Establish a method (ContentServiceOnSaving) that will fire when a user clicks 'save', or 'publish and save'. b) Target our desired content field to find our keyphrases. c) Parse the target content html against our keyphrase collection to create our internal/external links.

NB: If you just want to get the custom section up and running, you only need the ApplicationStarted method to create the KeyPhrase table.

    public class KeyphraseEvents : ApplicationEventHandler
    {
        private KeyphraseApiController _keyphraseApiController;

        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, 
                                           ApplicationContext applicationContext)
        {
            _keyphraseApiController = new KeyphraseApiController();
            ContentService.Saving += ContentServiceOnSaving;
            var db = applicationContext.DatabaseContext.Database;

            if (!db.TableExist("keyphrase"))
            {
                db.CreateTable<Keyphrase>(false);
            }
        }

        private void ContentServiceOnSaving(IContentService sender, SaveEventArgs<IContent> saveEventArgs)
        {
            var keyphrases = _keyphraseApiController.GetAll();
            var keyphraseContentParser = new KeyphraseContentParser();

            foreach (IContent content in saveEventArgs.SavedEntities)
            {
                if (content.ContentType.Alias.Equals("NewsArticle"))
                {
                    var blogContent = content.GetValue<string>("bodyContent");
                    var parsedBodyText = keyphraseContentParser.ReplaceKeyphrasesWithLinks(blogContent, keyphrases);
                    content.SetValue("bodyContent", parsedBodyText);
                }
            }
        }
    }

The ContentServiceOnSaving method allows us to intercept any save event in Umbraco. Afterwhich we check our incoming content to see if it's of the type we're expecting - in this example 'NewsArticle' - and if it is, then target the 'bodyContent' section, parse this with our 'KeyphraseContentParser', and swap the current 'bodyContent' with the parsed 'bodyContent'.

  1. Create a Keyphrase parser to swap keyphrases for internal/external links

    public class KeyphraseContentParser
    {
        public string ReplaceKeyphrasesWithLinks(string htmlContent,                                                        IEnumerable<Keyphrase> keyphrases)
        {
            var parsedHtmlStringBuilder = new StringBuilder(htmlContent);
    
            foreach (var keyphrase in keyphrases)
            {
                if (htmlContent.CaseContains(keyphrase.Phrase, StringComparison.OrdinalIgnoreCase))
                {
                    var index = 0;
                    do
                    {
                        index = parsedHtmlStringBuilder.ToString()
                        .IndexOf(keyphrase.Phrase, index, StringComparison.OrdinalIgnoreCase);
    
                        if (index != -1)
                        {
                            var keyphraseSuffix = parsedHtmlStringBuilder.ToString(index, keyphrase.Phrase.Length + 4);
                            var keyPhraseFromContent = parsedHtmlStringBuilder.ToString(index, keyphrase.Phrase.Length);
    
                            var keyphraseTarget = "_blank";
    
                            if (keyphrase.Link.StartsWith("/"))
                            {
                                keyphraseTarget = "_self";
                            }
    
                            var keyphraseLinkReplacement = String.Format("<a href='{0}' target='{1}'>{2}</a>",
    keyphrase.Link, keyphraseTarget, keyPhraseFromContent);
    
                            if (!keyphraseSuffix.Equals(String.Format("{0}</a>", keyPhraseFromContent)))
                            {
                                parsedHtmlStringBuilder.Remove(index, keyPhraseFromContent.Length);
                                parsedHtmlStringBuilder.Insert(index, keyphraseLinkReplacement);
                                index += keyphraseLinkReplacement.Length;
                            }
                            else
                            {
                                var previousStartBracket = parsedHtmlStringBuilder.ToString().LastIndexOf("<a", index);
                                var nextEndBracket = parsedHtmlStringBuilder.ToString().IndexOf("a>", index);
    
                              parsedHtmlStringBuilder.Remove(previousStartBracket, (nextEndBracket - (previousStartBracket - 2)));
                                   parsedHtmlStringBuilder.Insert(previousStartBracket, keyphraseLinkReplacement);
                        index = previousStartBracket +         keyphraseLinkReplacement.Length;
                            }
                        }
                    } while (index != -1);
                }
            }
    
            return parsedHtmlStringBuilder.ToString();
        }
    }
    

It's probably easiest to step through the above code, but fundamentally the parser has to:

a) find and wrap all keyphrases, ignoring case, with a link to an internal CMS, or external web resource.

b) handle an already parsed html string to both leave links in place and not create nested links.

c) allow CMS keyphrase changes to be updated in the parsed html string.

The blog of this, as well as the github code can be found from the links in the previous post.


Related:


Index was out of range. Must be non-negative or less than size of collection [duplicate]


c#
This question already has an answer here: What is an “index out of range” exception, and how do I fix it? [duplicate] 1 answer Trying to run a delete application in C#. If there is more than 10 files in a directory, delete the oldest file, and iterate again....

How to return result while applying Command query separation (CQS)


c#,design-patterns,cqrs,command-query-separation
I am separating my query and command on service side like this: public class ProductCommandService{ void AddProduct(Product product); } public interface ProductQueryService{ Product GetProduct(Guid id); Product[] GetAllProducts(); } Command Query Separation accepts that a method should change state or return a result. There is no problem. public class ProductController: ApiController{...

Merge and sum values and put them in an array


javascript,arrays,angularjs,foreach
I'm retrieving values from an external source and apply a foreach loop to the results, with the code below. angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { console.log(value.firstname + ' - ' + value.distance); } else { //do nothing } }); The result is console...

Validate a field only if it is populated


c#,wpf,idataerrorinfo
I am having a problem with validating phone numbers. In our system we have two phone numbers which you can store. The problem I am having is that these are optional fields. So I want it to validate the phone number IF and only IF the user has tried to...

Foreign key in C#


c#,sql,sql-server,database
I have two tables, A and B, in a dataset in SQL Server; I have created a connection to the dataset in a c# project in visual studio. How can I create a foreign key ( A is the parent) between my two tables ? I want to create the...

while Inherit style in WPF it affect parent style


c#,xaml,styles,wpf-controls
In WPF i have a style for the control like below, <Style TargetType="local:CustomControl"> <Setter Property="Background" Value="Transparent" /> <Setter Property="BorderBrush" Value="Gray" /> <Setter Property="BorderThickness" Value="0,0,0,1" /> <Setter Property="Padding" Value="3,0,3,0" /> <Setter Property="IsTabStop" Value="False" /> <Setter Property="VerticalContentAlignment" Value="Center" /> </Style> Now i need to override customcontrol border for some other place like...

Error: [$injector:unpr] Unknown provider: RestangularProvider <- Restangular <- ctrlAG


javascript,angularjs,restangular
I have one app: app.js: angular.module('AngApp', [ 'angularGrid' ]); My own restangular service.js: var app = angular.module('AngApp'); app.factory('restService', ['Restangular', function (Restangular) { // make use of Restangular } ]); and controller.js: var app = angular.module('AngApp'); app.controller('ctrlAG', ['$scope', '$http', '$log', '$mdDialog', 'Restangular',function ($scope,$http, $log, $mdDialog, Restangular) { // make use of...

Difference between application and module pipelines in Nancy?


c#,asp.net,nancy
I have seen in the documentation of Nancy, sometimes these two are referred distinctively. And also is there a difference in the Before/After hooks of these two pipelines?...

How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)


c#,.net,windows,sendkeys
I need to save a file which is in an External application using SendKeys.Send() method. The keys needed to be sent are Ctrl+S. I wrote the below code, but its not working: SendKeys.SendWait("^%s?"); // to get the Save As dialog Thread.Sleep(5000); SetForegroundWindow(FindWindow(null, "Save As")); Thread.Sleep(5000); SendKeys.SendWait("xyz"); // Sending FileName ...

Create angular page in Django to consume data from JSON


angularjs,django,django-templates
In an angular controller I have a list of items: app.controller('MainController', ['$scope', function($scope) { $scope.items = [ {"foo":"bar 1"}, {"foo":"bar 2"}, {"foo":"bar n"} ] }]); The following html page, based on angular, displays a list of item: <!DOCTYPE html> <html> <head> <title>list</title> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body data-ng-app="myApp"> <div data-ng-controller="MainController">...

REST API with token based authentication


angularjs,codeigniter,api,rest,token
I want to develop a web site with AngularJS. On the backend side I will use Codeigniter REST framework. I have some security issues and I don't want to start developing without fixing them on my mind. I don't want to use something like api key because it will be...

HTML elements in Angular bindings expression


html,angularjs
Is that possible to insert HTML elements in an Angular expression ? Let's take a few example. I would like to do something like this: <table> <tr ng-repeat="employee in employees"> <td>{{employee.firstname ? employee.firstname : '<p style="color:red">No name</p>'}}</td> <td>{{employee.job}}</td> </tr> </table> In our controller, we have: $scope.employees = [{firstname:'Bob', job:'Developer'}, {firstname:'Paul',...

Can't get angular.js to loop through array and post to html


angularjs,ng-repeat
Edit: changed ng-controller to ng-app in body tag, was typo I'm new to angular and im trying to use ng-repeat to post all items in the products[] to html but the {{expressions}} come out as text rather than computing. I don't have my laptop so I'm testing all this on...

Regex to remove `.` from a sub-string enclosed in square brackets


c#,.net,regex,string,replace
I have this regex in C#: \[.+?\] This regex extracts the sub-strings enclosed between square brackets. But before doing that I want to remove . inside these sub-strings. For example, the string hello,[how are yo.u?]There are [300.2] billion stars in [Milkyw.?ay]. should become hello,[how are you?]There are [3002] billion stars...

C# XML: System.InvalidOperationException


c#,xml
I have been learning C#'s XML with a project however I keep getting the InvalidOperationException. I have put the code below XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8); writer.WriteStartDocument(true); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartElement("User Info"); writer.WriteStartElement("Name"); writer.WriteString(userName); writer.WriteEndElement(); writer.WriteStartElement("Tutor Name"); writer.WriteString(tutorName); writer.WriteEndElement();...

C# Code design / Seperate classes for each TabControl


c#,oop,architecture,software-design,code-design
My main problem is that my tool grows and grows and I start loosing the focus on the different parts of my code. The main-Form got a docked tabControl at fullsize. I got 5 different tabs with for really different functions. So I can say my tool is splitted into...

Convert contents of an XmlNodeList to a new XmlDocument without looping


c#,xml,xpath,xmldocument,xmlnodelist
I have Xml that I filter using XPath (a query similar to this): XmlNodeList allItems = xDoc.SelectNodes("//Person[not(PersonID = following::Person/PersonID)]"); This filters all duplicates from my original Persons Xml. I want to create a new XmlDocument instance from the XmlNodeList generated above. At the minute, the only way I can see...

Why is the task is not cancelled when I call CancellationTokenSource's Cancel method in async method?


c#,asynchronous,task,cancellationtokensource,cancellation-token
I created a small wrapper around CancellationToken and CancellationTokenSource. The problem I have is that the CancelAsync method of CancellationHelper doesn't work as expected. I'm experiencing the problem with the ItShouldThrowAExceptionButStallsInstead method. To cancel the running task, it calls await coordinator.CancelAsync();, but the task is not cancelled actually and doesn't...

Socket.IO message doesn't update Angular variable


javascript,angularjs,node.js,sockets
I have a socket.io client-server setup with AngularJS running on the client. // Server.js var io = require('socket.io')(server); io.on('connection', function (socket) { socket.on('message', function (msg) { //console.log(msg); console.log(msg); io.emit('message', msg); }); }); As observed, it essentially emits a message events with the data stored in the variable msg. And then...

C# PCL HMACSHAX with BouncyCastle-PCL


c#,bouncycastle,portable-class-library
I want to implement this logic in portable C# class: static JsonWebToken() { HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>> { { JwtHashAlgorithm.HS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return sha.ComputeHash(value); } } }, { JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new...

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00


c#,asp.net,sql-server,date,gridview-sorting
I have a connected SQL Server database in Visual Studio and am displaying its content in a grid. I created a dropdown menu with the column names as selectable options and a text field to filter for specific content, e.g., DropDown = "Start" - Textfield = 14.03.2015 = Filter Column...

calling one controller from another controller


angularjs
I have 2 controllers and I am calling the second controller from the function of first controller $scope.open = function () { var modal = $modal.open({ templateUrl: 'views/view1.html', controller: 'controller2', // other parameters }); /* some code */ } Both the controllers are in the same folder. There are similar...

How do I provide a collection of elements to a custom attached property?


c#,wpf,binding
I found a few examples online, and a few questions and answers here, but I just can't get it to work. I need a custom attached property that can take one or more target elements. For example... <ListView> <dd:MyDragDrop.DropBorders> <Binding ElementName="brdOne"/> <Binding ElementName="brdTwo"/> <Binding ElementName="brdThree"/> </dd:MyDragDrop.DropBorders> </ListView> I've also had...

check if file is image


c#,asp.net,asp.net-mvc
I want to check if file is image. and then you will see a link where you can see the image. But the link only has to appear if file is link. I try it like this: if (!String.IsNullOrEmpty(item.FileName)) { var file = item.FileName; string[] formats = new string[] {...

How to use a service with Http request in Angular JS


javascript,angularjs
I'm using AngularJS to build my web application, I've been always using controllers to make HTTP request, which makes things easier and clear for me. But for a better code structure, and better execution for my application, I wanted to use services instead of controllers to use the web service....

Pre-Select of an option in a select not working


angularjs
I use the following select. Currently, I get empty options in my select on start. To avoid these empty options in angularJS, I want to preselect the first option in the select. But It do not work. I get an 'Cannot read property 'conditions' of undefined'. Thank you for your...

$http.get returns actual php script instead of running it (yeoman, grunt)


php,angularjs,pdo,gruntjs
I'm building a "simple" AngularJS app with an articles newsfeed. My articles are stored in a mysql database, and I extract them using php PDO. I used to do this using AJAX with a simple LAMP configuration (php5, mysql, apache2), and everything worked as intended. Now I'm trying to rebuild...

Visual Studio Assembly force-installs Target Framework


c#,.net,visual-studio-2013,.net-framework-version
I have this Assembly targeted at .NET 3.5. The code will work on later versions as well, but I like this to work on Windows XP. I mean, .NET is backwards compatible, right? I can run apps for .NET 3.5 on Windows 8.1. However, when I run my own assembly,...

How to Customize Visual Studio Setup


c#,visual-studio,setup-project
I have created a video chat application in c#. Now I wan to make a setup of it. I have created a setup using Visual studio's setup project but my client told me to customize the setup progress bar styles and other properties. i dont know how to do it....

Load XML to list using LINQ [duplicate]


c#,xml,linq
This question already has an answer here: XDocument to List of object 1 answer I have following XML: <?xml version="1.0" encoding="utf-8"?> <start> <Current CurrentID="5"> <GeoLocations> <GeoLocation id="1" x="78492.61" y="-80973.03" z="-4403.297"/> <GeoLocation id="2" x="78323.57" y="-81994.98" z="-4385.707"/> <GeoLocation id="3" x="78250.57" y="-81994.98" z="-4385.707"/> </GeoLocations> <Vendors> <Vendor id = "1" x="123456" y="456789" z="0234324"/>...

deployment of a site asp.net and iis


c#,asp.net,iis
I know this is for some of you a stupid question but for me is a real problem. I have never deployed a site before What i have done so far: 1) publish the site from visual studio to a folder. 2) added to iis for testing everything works great...

AngularJS: Adding ng-click within element.append


angularjs,directive
Within my directive I have the following code, which will be used to continually append to an html element. //Establishes the type of question and therefore what should be displayed app.directive('questionType', function ($http, $compile) { return { restrict: 'A', link: function (scope, element, attr, model) { switch (scope.Question.inputType) { case...

Marshal struct in struct from c# to c++


c#,c++,marshalling
I have the following structures in C# and C++. C++: struct TestA { char* iu; }; struct TestB { int cycle1; int cycle2; }; struct MainStruct { TestA test; TestB test2; }; C#: [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal struct TestA { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] private string iu; public...

Is it possible to concactenate a DataBound value with a constant string in XAML DataBinding?


c#,xaml,windows-phone
To bind a value to a TextBlock we use the following syntax to display an <ItemName> property of a bounded object. <TextBlock Text="{Binding Path=ItemName}" /> But is there a syntax to use the above tag to concatenate the constant string 'Item' with the databounded property, in order display something like:...

Multiple Threads searching on same folder at same time


c#,multithreading,file-search
Currently I have a .txt file of about 170,000 jpg file names and I read them all into a List (fileNames). I want to search ONE folder (this folder has sub-folders) to check if each file in fileNames exists in this folder and if it does, copy it to a...

Get object by attribute value [duplicate]


c#,reflection,custom-attributes,spring.net
This question already has an answer here: How enumerate all classes with custom class attribute? 4 answers I have a set of classes which implement a common interface and are annotated with a business domain attribute. By design, each class is annotated with different parametrization [Foo(Bar=1)] public class EntityA...

Angular $http and Fusion Tables in IE9


javascript,angularjs,internet-explorer-9,google-fusion-tables
I am trying a simple get request to a google fusion table in my angular controller. $http.get(url) .success(function(data) { //Do stuff with data }) This works in firefox, chrome, safari and IE10+ however in IE9 (Which I am requried to support) the request fails to even send and the console...

Access manager information from Active Directory


c#,asp.net,active-directory
Attach is the picture of active directory, which i got from my IT department. Now i want to get the manager information in C#. NOTE: I am able to get all information of user but there isn't any key of manager, but IT department just gave me above attached...

Can't save json data to variable (or cache) with angularjs $http.get


json,angularjs,web-services,rest
I have weird angularjs problem. I'm trying to fetch data from Rest Webservice. It works fine, but I can't save json data to object. My code looks like: services.service('customerService', [ '$http', '$cacheFactory', function($http, $cacheFactory) { var cache = $cacheFactory('dataCache'); var result = cache.get('user'); this.getById = function(id){ $http.get(urlList.getCustomer + id).success(function(data, status,...

Passing params to an angular service from a controller?


javascript,angularjs,service,controller,params
I'm an angular newby. I'm hoping to pass params to a service that fetches data form a server depending on those params. for example, if I want to pass a book name string and then use it in the service to concatenate with the request url. The documentation does not...

How to declare var datatype in public scope in c#?


c#,linq
I write simple query with linq to sql : var query = (from p in behzad.GAPERTitles select new { p.id, p.gaptitle }).ToArray(); up code into the c# windows application ,windows form load event,and i want use up result into the button click event in this scope: private void button1_Click(object sender,...

how can I add a column to IQueryable object and modify its values


c#,.net,linq,grid,devexpress
var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

Convert Date Time to IST


c#
I want to convert the date time to "Indian Standard Time", so i used the following code :- public static TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("Indian Standard Time"); writer.WriteLine("{0} {1}", indianTime.ToLongTimeString(), indianTime.ToLongDateString()); The above code gives me error :- System.TimeZoneNotFoundException: The time zone ID 'Indian Standard Time' was not found on the...

Aligning StackPanel to top-center in Canvas


c#,wpf,xaml,canvas
I'm trying to create an application which is supposed to measure quick reaction performance of it's user. The application starts up in full-screen mode and resizes it's elements accordingly to the screen resolution. The project was strongly inspired by training_aim_csgo2 map. It's mostly done, but here is the problem: I...

Catch concurrency exception in EF6 to change message to be more user friendly


c#,asp.net,.net,entity-framework,entity-framework-6
I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

Collect strings after a foreach loop


c#,xml,foreach
Is it possible to collect the strings after a foreach loop? For example: StringCollection col = new StringCollection(); XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name"); foreach (XmlNode skillNameNode in skillNameNodeList) { skillsName=skillNameNode.Attributes["value"].Value; } col.Add(skillsName); //Return System.Collections.Specialized.StringCollection I want to collect each skillsName and put them in a collection or a list so that I can...

System.net.http.formatting causing issues with Newtonsoft.json


c#,asp.net,asp.net-mvc,json.net
My Windows service is in the same solution as a MVC project. The MVC project uses a reference to SignalR Client which requires Newtonsoft.Json v6 + the Windows service uses System.Net.Http.Formatting, which requires Newtonsoft.Json version 4.5.0.0. I assumed this would not be a problem, as I could just use a...

How can I determine if an object of anonymous type is empty?


c#,.net
I am sure the answer to this is quite simple but I am trying to write an if statement (C# 5.0) to determine whether or not an anonymous type is empty or not. Here is a simplified version of my code: public void DoSomething(object attributes) { // This is the...

Memory consumption when chaining string methods


c#,string,immutability,method-chaining
I know that string in C# is an immutable type. Is it true that when you chain string functions, every function instantiates a new string? If it is true, what is the best practice to do too many manipulations on a string using chaining methods?...