Archive

Author Archive

Angular JS: Calling one controller from another controller

February 20, 2017 Leave a comment

Hi friends,

I came across a requirement where I am having multiple controllers referred on my page and I wanted to call one controller method from another controller.

This is common sacnorao while dealing with multiple controllers.

Problem statement:

Calling one controller method from another controller.

Solution:

We need to use ‘$emit’ and ‘$on’ services for event based communication and expose the function to other controller on $rootScope.

Following code explains how we can achieve this.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.js">
</script>
<script>
var myApp = angular.module('MyTest', []);
myApp.controller('My1Controller', function($scope,$rootScope) {
  $scope.childmethod = function() {
            $rootScope.$emit("CallMy2ControllerMethod", {message: 'in My Controller 2'});
        }
		
		$scope.childmethod2 = function() {
            $rootScope.$emit("CallMy3ControllerMethod", {message: 'in My Controller 3'});
        }
});
myApp.controller('My2Controller', function($scope,$rootScope) {
   $rootScope.$on("CallMy2ControllerMethod", function(event,param1){
           $scope.My2ControllerMethod(param1);
        });

        $scope.My2ControllerMethod = function(param1) {
			alert(param1.message);
        }
});
myApp.controller('My3Controller', function($scope,$rootScope) {
  $rootScope.$on("CallMy3ControllerMethod", function(event,param1){
           $scope.My3ControllerMethod(param1);
        });

        $scope.My3ControllerMethod = function(param1) {
			alert(param1.message);
        }
});
</script>
</head>
<body ng-app="MyTest">
<div ng-controller="My1Controller">
This is "Controller 1"
 <input type="button" value="Call My2Controller" ng-click="childmethod()">

 <input type="button" value="Call My3Controller" ng-click="childmethod2()"></div>
<div ng-controller="My2Controller"></div>
<div ng-controller="My3Controller"></div>
</body>
</html>

In above example we are calling My2Controller and My3Controller methods from My1Controller.

We have made method ‘CallMy2ControllerMethod’ and ‘CallMy3ControllerMethod’ available using ‘$on’ and we can call the method using $emit.

There is another way to use ‘$broadcast’ and ‘$on’ but it’s better to use ‘$emit’ and ‘$on’ as it destroys the listener.

Hope this will help some of the developers.

Angular JS: DataType gets added in value for ng-options when accessing value outside of angular scope

January 12, 2017 Leave a comment

Hi Friends,

While working on Angular JS I came across an issue where value data type got added to option value.

Problem statement:

Check the following ng-options binding.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
 angular.module("BlogTest", []).
 controller("BlogTestController", ["$scope", function($scope) {
 $scope.users = [
 {userId: 101, userName: "One"},
 {userId: 102, userName: "Two"},
 {userId: 103, userName: "Three"}
 ];
 $scope.calculateQuantity = function() {
 var e = document.getElementById("ddlusers");
 var strUser = e.options[e.selectedIndex].value;
 $('#angularselected').html($scope.users1); // output as 101,102,103
 $('#javascriptselected').html(strUser); // output as number:101, number:102, number:103
 $('#jqueryselected').html($("#ddlusers").val()); // output as number:101, number:102, number:103
 };
 }]);
</script>
</head>
<body>
<div ng-app="BlogTest" ng-controller="BlogTestController">
<select ng-model="users1" id="ddlusers" ng-options="user.userId as user.userName for user in users">
</select></br>
Angular selected :: <span id="angularselected"></span></br>
JavaScript selected :: <span id="javascriptselected"></span></br>
jQuery selected :: <span id="jqueryselected"></span></br>
<input type="button" value="Selected value" ng-click="calculateQuantity()"></div>
</body>
</html>

Above code binds the option perfectly but when if we try to access the value outside the angular scope we found that value is getting added with data type of value.

Below screen shot showing the difference between accessing the value within the scope and outside the scope using JavaScript or jQuery.

view1

view2

view3

If you check the rendered HTML you will found as following where datatype gets added in value

view4

Solution:

The solution to this is to use ‘track by’ as shown in below code snippet.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
 angular.module("BlogTest", []).
 controller("BlogTestController", ["$scope", function($scope) {
 $scope.users = [
 {userId: 101, userName: "One"},
 {userId: 102, userName: "Two"},
 {userId: 103, userName: "Three"}
 ];
 $scope.calculateQuantity = function() {
 var e = document.getElementById("ddlusers");
 var strUser = e.options[e.selectedIndex].value;
 $('#angularselected').html($scope.users1); // output as 101,102,103
 $('#javascriptselected').html(strUser); // output as number:101, number:102, number:103
 $('#jqueryselected').html($("#ddlusers").val()); // output as number:101, number:102, number:103
 };
 }]);
</script>
</head>
<body>
<div ng-app="BlogTest" ng-controller="BlogTestController">
<select ng-model="users1" id="ddlusers" ng-options="user.userId as user.userName for user in users track by user.userId">
</select></br>
Angular selected :: <span id="angularselected"></span></br>
JavaScript selected :: <span id="javascriptselected"></span></br>
jQuery selected :: <span id="jqueryselected"></span></br>
<input type="button" value="Selected value" ng-click="calculateQuantity()"></div>
</body>
</html>

Now if you see the result, you will find that datatype got removed from the source HTML

view10

And the result now for Angular and non-angular is same.

view7

view8

view9

Happy coding and Happy New Year 2017.

SharePoint 2013: Modal Dialog position and scrolling issue with lengthy page

We have come across an issue with SharePoint modal dialog, while working with a lengthy page where due to some lengthy content vertical scroll bar were coming. We developed one web part form, which we have added at the center of the vertical screen. From that web part we can open a SharePoint Asset picker to select the image which opens a model dialog. The functionality was working as expected but we found an UI level issues.

Problem: When we try to launch SharePoint ‘Modal Dialog’ from the bottom of the huge scrolled page, we are not able to see the dialog and only see the bluer screen (overlay). The actual model dialog is getting opened at the top of the page and because of the current scroll position which is somewhere in between the screen or at the bottom, we are not able to see the popup.

Solution: The model dialog location is set by CSS class on the top of the screen, we need to override the css class to change the property. The name of the class is ms-dlgContent. We can add following css class in either master page or respective CSS.

.ms-dlgContent
{
position:fixed! important;
}

SharePoint 2013: Exception while creating default associated groups through PowerShell

While new site collection provisioned default security groups been provisioned when we create it from central administration but not when the site collection was created using script. For that we need to call a function ‘CreateDefaultAssociatedGroups’. This method actually created default associated group example member, Owner and Visitor group and add the group owner as the first parameter provided to the method call.

When I tried it some cases it worked and in some cases I was getting error “Exception calling “CreateDefaultAssociatedGroups” with “3” argument(s): “User cannot be found”

While analyzing the issue the issue I found that I am passing only first mandatory parameter as the user logon name of the group owner. Like –

$sps_web.CreateDefaultAssociatedGroups("MyDomian\spadmin","","");

And then I was getting error Exception calling “CreateDefaultAssociatedGroups” with “3” argument(s): “User cannot be found.” And the default groups are not getting added.

Further analysis concluded that the user I was passing as group owner was not getting added and hence the exception is thrown.

We have used EnsureUser before calling CreateDefaultAssociatedGroups function to make sure that before the call user should be available in user information list like –

$sps_web.EnsureUser("MyDomian\spadmin");
$sps_web.CreateDefaultAssociatedGroups("MyDomian\spadmin","","");

SharePoint 2013: Getting lookup column values in JSLink

Hi Friends,

While working on of the development requirement related to JSLink I came across a scenario where a lookup value needed to be shown in a list view web part.

I wanted to demonstrate with following code how we can achieve to show the lookup values form single valued or multi valued lookup.

Before that I would like to show the relationship between the lists I used to show the demonstration.

I have created following two custom lists for demonstration.

First list with following column –

TestList2

 

The content in First list will like something –

TestList2Content

Second list having lookup column from first list –

TestList1

 

The content in second list like following –

TestList1Content

Following code will show how to get the single or multi valued lookup values and show.


(function () {

var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.Templates.Item = CustomPortalPageItem;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();
function CustomPortalPageItem(ctx) {
var html = "";
html += '<div title="' + ctx.CurrentItem.Title + '"></div><div>'+GetLookupValues(ctx.CurrentItem.Test11,"lookupValue")+'</div>';
return html;
}

function GetLookupValues(inputArry,originalColumnName)
{
var retHtml="";
if(inputArry!=null)
{
for(var loopcnt=0;loopcnt<inputArry.length;loopcnt++)
{
if (typeof(inputArry[loopcnt][originalColumnName]) != 'undefined' && inputArry[loopcnt][originalColumnName] != null)
{
retHtml+=inputArry[loopcnt][originalColumnName];
}
}
}
return retHtml;
}

After this it will look like following,you can then apply beautiful HTML to it.
JSLInkOP

SharePoint 2013: Designer workflow error with ‘Call HTTP web service’ action

February 17, 2015 4 comments

While working on one of the workflow development task, it was required to have a web service call to fetch data from SharePoint. To achieve that I used ‘Call HTTP web service’ action but with that I was getting following exception “Unable to deserialize HTTP response content. Expected Content Type: ‘application/json’, ‘text/plain’ or ‘text/html’”.

Suspended

After struggling with this issue, the solution I used thought to share the solution with developer community.

Solution: The reason for the issue is, by default response from SharePoint REST is in XML and SharePoint designer workflow not able to parse the xml and needs JSON response. To resolve this issue we need to pass Accept and Content-Type as application/json;odata=verbose to request headers. This way we will get JSON response. To resolve this follow bellow steps.

  1. Go to SharePoint 2013 designer.
  2. Build a Dictionary variable named ‘WSHearder’WF1
  3. Add two values in newly created dictionary
Accept = application/json;odata=verbose
Content-Type = application/json;odata=verbose
WF2
  1. Now select ‘Call HTTP web service’ action and select Properties.              WF3
  2. Select newly created dictionary variable as value for ‘RequestHeaders’.WF4
  3. Press OK and publish the workflow.

SharePoint 2013: Querying SharePoint log files

December 31, 2014 Leave a comment

Hi Friends,

While working as a SharePoint developer every one of us need to go to SharePoint log files to check exact nature and cause of error. SharePoint logs provide us vital information to resolve the issue. SharePoint provides us correlation id to get the details about the issue, but it is difficult some times to go and check the log files and manually find the error in log and get the cause, as log files are huge sometimes.

To resolve this we have some PowerShell cmdlets which we can use to search in log files. Some of them are Get-SPLogEvent and Merge-SPLogFile. We can discuss about them in more detail below.

1. Get-SPLogEvent-

We can use Get-SPLogEvent to query log files when either single server farm in place or we have knowledge on which server the error gets logged.So Get-SPLogEvent will query the logs in the same server where PowerShell command gets executed.Some of the samples below –

get-splogevent | ?{$_.Message -like "*Monitored*" -and $_.Correlation -eq "2713db9c-f21e-e0bc-3393-95ddcbf60bd0"} | select Area, Category, Level, EventID, Message | Format-List > C:\Log1.log

Above command will search with specified correlation id and get the content where message contains ‘Monitored’ word and dump the requested fields (Area, Category, Level, EventID, Message) in file Log1.log

get-splogevent | ?{$_.Correlation -eq "2713db9c-f21e-e0bc-3393-95ddcbf60bd0"} | select Area, Category, Level, EventID, Message | Format-List > C:\Log2.log

Above command will search with specified correlation id and dump the requested fields (Area, Category, Level, EventID, Message) in file Log2.log at specified path

You can use the above commands directly also on powershell to get the details directly instead of creating a file out of it, like

get-splogevent | ?{$_.Message -like "*user*" -and $_.Correlation -eq "2713db9c-f21e-e0bc-3393-95ddcbf60bd0" -and $_.Level -eq "Medium" -and $_.Category -eq "App Deployment"} | select Area, Category, Level, EventID, Message

Above command will search with specified correlation id and get the content where message contains ‘user’ word , Level is ‘Medium’ and Category equals ‘App Deployment’ and display the requested fields (Area, Category, Level, EventID, Message) on PowerShell window.

get-splogevent -StartTime "12/11/2014 10:00" -EndTime "12/12/2014 18:00"

Above command will search the logs with specified date range and display on PowerShell window.

2. Merge-SPLogFile-

We can use Merge-SPLogFile to query log files when we have a scenario where mult-server farm in place and we do not have idea where exactly the error get logged. i.e. timer service is running on four servers and the current timer request is served by Server1 then error get logged on server1. Some of the samples below –

Merge-SPLogFile -Path "C:\Log1.log" -Overwrite -Message "*Monitored*" – Correlation "2713db9c-f21e-e0bc-3393-95ddcbf60bd0"

Above command will search with specified correlation id and get the content where message contains ‘Monitored’ word and dump the details in file Log1.log

Merge-SPLogFile -Path "C:\Log2.log" -Overwrite -Message "*Monitored*" – Correlation "2713db9c-f21e-e0bc-3393-95ddcbf60bd0"

Above command will search with specified correlation id and dump the details in file Log2.log

Merge-SPLogFile -Path "C:\Log3.log" -Overwrite -StartTime "12/11/2014 10:00" - EndTime "12/12/2014 18:00"

Above command will search the logs with specified date range and dump the details in file Log3.log.
Hope this will reduce some of the debugging efforts.

“As the year comes to an end, don’t look back at yesterday’s disappointment. Look ahead to God’s promises yet to unfold.” ― Buky Ojelabi, comtemporary blogger
Happy new year 2015.