Total Pageviews

Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

28 Nov 2018

Visual Studio Code: Black screen issue. Fix

If you are like me and you had an annoying issue with Visual Studio code that caused a black scree then you will like this fix.

My old fix:
code --disable-gpu

This was launching VS Code without GPU acceleration. It was a workable solution, but still very inconvenient.

New, permanent fix:
- Open your Nvidia Control panel
- Set Physx Configuration
- Under Select a physX processor select "CPU":




23 Jun 2018

Creating Forms for SharePoint Online using PowerApps, AngularJs, React or Nintex

Here my short presentation on the best options of creating forms in office 365, SharePoint Online

Disclaimer. I've made a couple of mistakes:
1. There is no mobile app for Microsoft Forms. But it MS Forms links open fine in any mobile browser. I guess there is no point in having the app in the first place.
2. The last app I've demonstrated was written using React+TypeScript, not AngularJs.

7 Oct 2016

Hide Attachments from specific SharePoint Group

 <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js' type="text/javascript">  
 </script>  
 <script type="text/javascript">  
   $(function() {  
     $.ajax({  
       url: "/_api/web/currentUser?$select=Groups/Title&$expand=Groups",  
       method: "GET",  
       headers: {  
         "Accept": "application/json; odata=verbose"  
       },  
       success: function(data) {  
         for (var k = 0; k < data.d.Groups.results.length; k++) {  
           var groupName = data.d.Groups.results[k].Title;  
           if (groupName == 'OECTA EXEC GL') {  
             $("[scriptclass='SharePointFileAttachmentCollection'], [scriptclass='SharePointFileAttachmentContainer']").hide();  
           }  
         }  
       },  
       error: function(data) {  
         console.log(data);  
       }  
     });  
   });  
 </script>  

23 Apr 2015

Override Keyboard Keys in SharePoint

Here is a simple way to override keyboard keys in SharePoint:


 overrideKeys = function () {  
 /*This is a standard SharePoint Function, that listens to keyboard events*/  
   window.OnListViewKeyDown = function OnListViewKeyDown(a, b) {  
     var d = GetListContextFromContextNumber(String(b));  
     if (d == null || d.inGridMode) return;  
     var e = a.keyCode,  
       c = a.shiftKey || a.ctrlKey;  
     if (IsCallOutOn()) return;  
           console.log(e);  
     switch (e) {  
       case Sys.UI.Key.del:  
         //Oveeride Delete Button  
         break;  
       case Sys.UI.Key.up:  
         SelectNextRow(b, -1, c, a);  
         break;  
       case Sys.UI.Key.down:  
         SelectNextRow(b, 1, c, a);  
         break;  
       case Sys.UI.Key.enter:  
         if (IsEventTargetAnchor(a)) return;  
         if (a.target != null && !IsStrNullOrEmpty(a.target.className) && a.target.className.indexOf("ms-lstItmLinkAnchor") >= 0) OpenCallOutOrECB(b, a);  
         else ListItem_Open(b, a)  
           case Sys.UI.Key.esc:  
                 //override Esc  
                 brea;  
     }  
   }  
 };  
 $(function () {  
   setTimeout(overrideKeys, 600);  
 });  
You can have a look at the full list of Sys.UI.Keys here

18 Jan 2014

Check if a Field was Changed Inside ItemUpdated Handler of a List EventReceiver

I think, I found the easiest way to check if a particular field was changed inside ItemUpdated handler. Here is what you should do:
  1. Add a new hidden field to the list.
  2. Register a new EventReceiver for ItemUpdating. It will save previous field values.
  3. In ItemUpdating save a field value from before properties of the field to afterProperties of the hidden field.
  4. In ItemUpdated compare afterProperties of the wanted field with the after properties of the hiddenField
2. Registering event receivers inside a feature receiver with the web scope:


 private static void AddEventReceivers(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb) properties.Feature.Parent;
            string assembly = Assembly.GetExecutingAssembly().FullName;

            web.AllowUnsafeUpdates = true;

            SPList list = GetTheListSomehow();
            SPEventReceiverDefinition ERDefinitionUpdated = list.EventReceivers.Add();
            ERDefinitionUpdated.Assembly = assembly;
            ERDefinitionUpdated.Class = typeof(Event_Receiver_Class).FullName;
            ERDefinitionUpdated.Type = SPEventReceiverType.ItemUpdated;
            ERDefinitionUpdated.Name = "ClipsEventReceiverItemUpdated";
            ERDefinitionUpdated.Update();

            SPEventReceiverDefinition ERDefinitionUpdating = list.EventReceivers.Add();
            ERDefinitionUpdating.Assembly = assembly;
            ERDefinitionUpdating.Class = typeof(Event_Receiver_Class).FullName;
            ERDefinitionUpdating.Type = SPEventReceiverType.ItemUpdating;
            ERDefinitionUpdating.Name = "ClipsEventReceiverItemUpdating";
            ERDefinitionUpdating.Update();
}


3. ItemUpdating EventReceiver:

public override void ItemUpdating(SPItemEventProperties properties)
{
    //warning: you should check if the field is not null
    properties.AfterProperties["hiddenFieldName"] = properties.ListItem["fieldName"];
}
warning: do not try to save values straight the hidden field. You should use afterProperties instead like is shown above.

4. ItemUpdated EventReceiver:

public override void ItemUpdated(SPItemEventProperties properties)
{
   string oldfieldValue = properties.ListItem["hiddenField"];

    //simplified example. you should check for nulls and maybe use a better way of comparing field values
   if (String.Equals(oldfieldValue, properties.AfterProperties["fieldName"]))
   {
       return;
   }
   //some code...
}



4 Jan 2014

Using AppFabric Programmatically on SharePoint 2013 Farm

First of all, if you are going to use standard App Fabric cluster that goes with the prerequisites for SharePoint 2013 you'll end up being unsupported by Microsoft:

If you are using custom applications in SharePoint Server 2013 which use the AppFabric client APIs, or are creating custom caches, you should create a separate AppFabric cache cluster to support your custom applications. Do not use the AppFabric cache cluster supporting your SharePoint Server 2013 farm. Run your separate AppFabric cache cluster for your custom applications on separate servers from the servers dedicated to your SharePoint Server 2013 farm.

If you still want to use the OOB AF cluster, here is a sample code for it:

 static void Main(string[] args)
    {
        List<DataCacheServerEndpoint> servers = new List<DataCacheServerEndpoint>();
        servers.Add(new DataCacheServerEndpoint("server.domain", 22233));
        DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration();
        configuration.ChannelOpenTimeout = TimeSpan.FromSeconds(120);
        configuration.IsCompressionEnabled = false;
        configuration.MaxConnectionsToServer = 10;
        configuration.RequestTimeout = TimeSpan.FromSeconds(120);
        configuration.Servers = servers;
        configuration.TransportProperties.MaxBufferSize = 1000000;
        DataCacheFactory dataCacheFactory = new DataCacheFactory(configuration);
        DataCache cache = dataCacheFactory.GetCache("DistributedDefaultCache_" + SPFarm.Local.Id);

        if (cache.Get("MyKEY") == null)
        {
            cache.Add("MyKEY", DateTime.Now);
        }
        DateTime dt = (DateTime)cache.Get("MyKEY");
        Console.WriteLine(dt);
    }

Note that you need to get the list of all servers in your cluster. In order to do it dynamically, you can use this piece of code:
string cacheClusterName = "SPDistributedCacheCluster_" + SPFarm.Local.Id;
var cacheClusterManager = SPDistributedCacheClusterInfoManager.Local;
var cacheClusterInfo =     cacheClusterManager.GetSPDistributedCacheClusterInfo(cacheClusterName);

foreach (var cacheHost in cacheClusterInfo.CacheHostsInfoCollection)
{
  servers.Add(new DataCacheServerEndpoint(cacheHost.HostName, cacheHost.CachePort));
}
I've also found a very decent helper class for working with OOB App Fabric cache (credits to Bernado Nguyen-Hoan).

9 Nov 2013

ShowField="NameWithPicture attribute breaks field rendering in SharePoint 2013

I've noticed that  ShowField="NameWithPicture" attribute  in SharePoint 2013 does not render properly:



So, instead of NameWithPicture value
<Field Name="Employee" ID="{33c2ee31-2927-4de3-8e7d-cc1f2676378b}" DisplayName="Сотрудник" Type="User" Required="TRUE" UserSelectionMode="PeopleOnly" UserSelectionScope="0" ShowField="NameWithPicture" /

you can use NameWithPictureAndDetails:
<Field Name="Employee" ID="{33c2ee31-2927-4de3-8e7d-cc1f2676378b}" DisplayName="Сотрудник" Type="User" Required="TRUE" UserSelectionMode="PeopleOnly" UserSelectionScope="0" ShowField="NameWithPictureAndDetails" />

The result should look simillar to:


I've also noticed, that you can also change the way user field is displayed. There is a number of ways this field can be rendered. Honestly, I had no idea you could do that!

Update (Solution #2):
Looks like after updating Visual Studio Projects from SP2010 to SP 2013 you can include <JSLink>clienttemplates.js</JSLink> node into your View in schema.xml:


This will allow you to render User field with  ShowField="NameWithPicture" properly.


4 Jun 2013

SharePoint 2010. Open 'Browse' Ribbon Tab by Default

Just include InitialTabID=Ribbon.Read in your URL parameter:
 http://site/List1/Forms/DispForm.aspx/&InitialTabID=Ribbon.Read 

29 May 2013

Detect Edit Mode with Javascript on SharePoint pages or SPListitem forms

This JavaScript function will tell you if we are in the List Edit form:

var isEditForm = function ()
{
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    if (sPage == "EditForm.aspx")
    return true;
    else return false;
}


And this one will tell you if we are in edit mode on publishing, web part or wiki pages
var isinEditMode = function() {
    var isEditMode = false;
    try {
        var inDesignMode = document.forms[window.MSOWebPartPageFormName].MSOLayout_InDesignMode.value;

        if (inDesignMode == "1") {
            isEditMode = true;

        }
    } catch(e) {
    }

    try {
        var wikiInEditMode = document.forms[window.MSOWebPartPageFormName]._wikiPageMode.value;
        if (wikiInEditMode == "Edit") {
            isEditMode = true;
        }
    } catch(e) {

    }

    return isEditMode;
};

28 Apr 2013

SharePoint 2013. New JSLink property for SPField


This is a side note about the use of JSLink property in SPFields. I intend to use this later in my projects. Here are 2 simple steps.

1.Create and deploy JS Field with the script that looks like this:

2. Change the new JSLink property for you SPField like is show on the screenshot. Note that it may be even built-in field.

The result should look like this. I've added a simple "refresh" image inside the field as a test.

For more info you could check this nice article SP 2013: Using the JSLink property to change the way your field or views are rendered in SharePoint 2013

6 Feb 2013

Opening Modal Dialog on Custom Action

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
                Description="Create Dialog With Scenario"
                Sequence="10001"
                GroupId="SiteActions"
                Id="DialogSiteCustomAction"
                Location="Microsoft.SharePoint.StandardMenu"
                ImageUrl="/_layouts/Images/Asteros.KPZSZF/Megafon.jpg"
                Rights="AddListItems" Title="Create Dialog">
  <UrlAction Url="javascript:OpenPopUpPageWithTitle('/_layouts/CustomSPCF/customspcf.aspx', RefreshOnDialogClose, 640, 610,'Create Dialog')"/>
</CustomAction>
</Elements>

11 Jan 2013

Testing SharePoint Server Search with KeywordQuery


Code:
   class Program
    {
        static void Main(string[] args)
        {

            SearchQueryAndSiteSettingsServiceProxy settingsProxy = SPFarm.Local.ServiceProxies.GetValue<SearchQueryAndSiteSettingsServiceProxy>();

            SearchServiceApplicationProxy searchProxy = settingsProxy.ApplicationProxies.GetValue<SearchServiceApplicationProxy>("Enterprise Search Service");

            KeywordQuery keywordQuery = new KeywordQuery(searchProxy);

            keywordQuery.QueryText = "Region:b2a48ce5-31e0-40f7-873b-f4fbceacc45f";

            keywordQuery.SelectProperties.Add("Title");
            keywordQuery.SelectProperties.Add("Region");
            keywordQuery.SelectProperties.Add("Регион");
            keywordQuery.SelectProperties.Add("ItemSection");

            //The creator of this fault did not specify a Reason:
           // keywordQuery.SelectProperties.Add("owsMetadataFacetInfo");
            
           // keywordQuery.SelectProperties.Add("owstaxIdRegion");

            keywordQuery.ResultsProvider = SearchProvider.Default;

            keywordQuery.ResultTypes = ResultType.RelevantResults;

            keywordQuery.RowLimit = 50;

            ResultTableCollection resultsTableCollection = keywordQuery.Execute();

            ResultTable searchResultsTable = resultsTableCollection[ResultType.RelevantResults];

            DataTable resultsDataTable = new DataTable();

            resultsDataTable.TableName = "Results";

            resultsDataTable.Load(searchResultsTable, LoadOption.OverwriteChanges);

            Console.WriteLine(resultsDataTable.Rows.Count);

            for (int j = 0; j < resultsDataTable.Rows.Count; j++)
            {

                DataRow row = resultsDataTable.Rows[j];
                foreach (DataColumn column in resultsDataTable.Columns)
                {
                    Console.Write("Item: ");
                    Console.Write(column.ColumnName);
                    Console.Write(" ");
                    Console.WriteLine(row[column]);
                }
            } 
        }
    }


Code:
     using(SPSite site = new SPSite("http://portal.com"))
            {
                SearchServiceApplicationProxy ssa = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(site));

                KeywordQuery kq = new KeywordQuery(ssa);
                kq.ResultsProvider = SearchProvider.Default;
                kq.QueryText = string.Format(CultureInfo.InvariantCulture, "scope:\"{0}\"; title:\"Ivanov Ivan\"", "people");
                kq.ResultTypes = ResultType.RelevantResults;
                kq.StartRow = 0;
                kq.EnablePhonetic = true;
                kq.EnableStemming = true;
                kq.RowLimit = 1000;
                kq.KeywordInclusion = KeywordInclusion.AllKeywords;

                ResultTableCollection res = kq.Execute();

                bool exists = res.Exists(ResultType.RelevantResults);

                if (exists)
                {
                    ResultTable searchResult = res[ResultType.RelevantResults];
                    Console.WriteLine(searchResult.TotalRows);
                }

                
            }
            Console.ReadLine();


Adding a warm-up step to your SharePoint project deploy action

I've recently found a very useful blog post on how to improve SharePoint Deployment experience in Visual Studio.

Check this out!