Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Tuesday, 2 April 2024

Move git repository to another server

git remote rm origin 
git remote add origin http://... 
git push -u origin --all

Sunday, 26 March 2023

Dodanie nowego komponentu - app.module.ts


  1. import { YourNameComponent } from './pages/admin/YourName/YourName.component';

  2. appRoutes: Routes = [
    {
    path: 'admin/YourName',
    component: YourNameComponent,
    canActivate: [AuthenticationGuard],
    data: { title: 'Your Name', isNew: true }
    },

  3. @NgModule({
      declarations: [
        YourNameComponent

Saturday, 25 March 2023

Preparing Dev Env for Angular

Install software
1. Install Visual Studio Code
2. Install Git
3. Install Node.js

Configure Angular with NPM (node package manager)

1. install Angular CLI - use command prompt or VS Code terminal
npm install -g @angular/cli
2. install SASS
npm install -g node-sass
3. To create new Angular project with SASS as default style:
ng new project-name-here --style=scss
4. To create new Angular component:
ng generate component name-here

Thursday, 25 August 2022

Using process.env in React

  1. Install dotenv package
  2. Create .env file in root directory
  3. Add variables to the file like this:
REACT_APP_MOCK_API_URL=data1
REACT_APP_REST_KEY=data2

  1. Read variables like this:

const key = process.env.REACT_APP_REST_KEY;
const mockUrl = process.env.REACT_APP_MOCK_API_URL;

Important!

Variable name MUST begin with "REACT_APP_"

(Initially I called variable MOCK_API_URL. It took me few hours to figure out why key contained value and mockUrl was undefined.)


Friday, 11 February 2022

Jak usunąć pliki z poprzedniej instalacji Windows, do których nie ma dostępu

takeown /F "D:\Program Files" /A /R /D Y
icacls "D:\Program Files" /T /grant administrators:F
rd /s /q "D:\Program Files"

Tuesday, 20 October 2020

Implementing ControlValueAccessor


import { Component, forwardRef, Input, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-password-input',
  templateUrl: './password-input.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PasswordInputComponent),
      multi: true
    }
  ]
})
export class PasswordInputComponent implements OnInit, ControlValueAccessor {
  constructor() {}
  writeValue(obj: any): void {
    this.Value = obj;
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouch = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
  onChange: any = () => {};
  onTouch: any = () => {};
  disabled?: boolean;
  ngOnInit(): void {}

  /** Password value */
  public value: string;
  set Value(val) {
    // this value is updated by programmatic changes
    if (val !== undefined && this.value !== val) {
      this.value = val;
      this.onChange(val);
      this.onTouch(val);
    }
  }
  get Value(): string {
    return this.value;
  }
 }

Thursday, 1 October 2020

Custom Events with Angular Elements

Created component in Angular, it has Output called selectedStep, that emits a number.
@Output() public selectedStep: EventEmitter<number> = new EventEmitter<number>();
How to write CustomEvent in plain HTML + JS page, so that it would eg. display step number to console?
<script>
// trigger this function, when event is emitted from inside custom-element
function stepChanged(e) {
  console.log('Current step: ' + e);
}

document.addEventListener("DOMContentLoaded", function() {
  // Handler when the DOM is fully loaded
  let element = document.querySelector("custom-element");
  element.addEventListener("selectedStep", event => {
    stepChanged(event.detail);
  });
});

</script>
<custom-element></custom-element>
Important to remember: 
  1. addEventListener first parameter is the name of Output 
  2. Emitted value is in detail property of second paramenter

Wednesday, 23 September 2020

TypeScript - generate random word

This method will generate random string of n-letter length with lowercase letters:
  /**
   * Generate random lowercase word
   * @param {number} length Word length
   * @returns Random n-letter word
   */
  randomWord(length: number): string {
    let result = '';
    for (let index = 0; index < length; index++) {
      // one of 26 en letters, 'a' = 97
      const ascii = Math.floor(Math.random() * 26 + 97);
      result += String.fromCharCode(ascii);
    }
    return result;
  }

Tuesday, 1 September 2020

Hide Addons panel for some stories in Storybook

I'm using Code Preview globally in Storybook with storybook-addon-preview. However, I there is one story that has no code preview and it displays "No Preview found" message.
To hide the panel for single story, set following parameters in Story:
export default {
  title: 'Some title',
  parameters: { options: { showPanel: false } }
};

Friday, 17 July 2020

Bootstrap in Storybook

To use Bootstrap modules in Storybook, you have to import NgbModule inside the story and then in the story say:
export default {
    title: 'Tooltip',
    decorators: [
        moduleMetadata({
            // imports both components to allow component composition with storybook
            declarations: [TooltipComponent],
            imports: [NgbModule]
        }),
    ],
};

Wednesday, 5 November 2014

How to fetch more than 5000 entities from CRM

Let's start with simple example to get all entities from CRM

public EntityCollection GetEntities(string entityName)
{
    var config = ServerConnection.GetServerConfiguration();
    var proxy = ServerConnection.GetOrganizationProxy(config);

    string request = string.Format(@"<fetch mapping ='logical'>
               <entity name = '{0}'></entity></fetch>", entityName);
    FetchExpression expression = new FetchExpression(request);
    var mult = proxy.RetrieveMultiple(expression);

    return mult;           
}
This will work, but will return maximum of 5000 elements in mult.Entities.
Let's add paging now and put that in loop until mult.MoreRecords is false.

string request = string.Format(@"<fetch
                count='5000' page='{1}' mapping ='logical'>
                <entity name = '{0}'></entity></fetch>"
, entityName, page++);
But now Paging cookie is required when trying to retrieve a set of records on any high pages.
Paging cookie is returned in EntityCollection.PagingCookie property. Also, XML tags must be encoded, because this is xml-in-xml.

pagingCookie = string.Format("paging-cookie='{0}'",
    System.Web.
HttpUtility.HtmlEncode(mult.PagingCookie));

Now, complete method looks like this:

public IList<Entity> GetEntitiesNoLimit(string entityName)
{
    var config = ServerConnection.GetServerConfiguration();
    IOrganizationService proxy = ServerConnection.GetOrganizationProxy(config);

    var entities = new List<Entity>();
    int page = 1;
    string pagingCookie = string.Empty;
    while (true)
    {
        string request = string.Format(@"<fetch {2} count='5000' page='{1}'
                         mapping ='logical'><entity name = '{0}'></entity></fetch>",
                         entityName, page++, pagingCookie);
        FetchExpression expression = new FetchExpression(request);
        var mult = proxy.RetrieveMultiple(expression);
        entities.AddRange(mult.Entities);
        if (mult.MoreRecords)
        {
            pagingCookie = string.Format("paging-cookie='{0}'",
                        System.Web.HttpUtility.HtmlEncode(mult.PagingCookie));
        }
        else
        {
            break;
        }
    }

    return entities;
}

Monday, 27 October 2014

Drop all foreign keys

DECLARE @SQL varchar(4000)=''
SELECT @SQL = @SQL + 'ALTER TABLE ' + FK.TABLE_NAME + ' DROP CONSTRAINT [' + RTRIM(C.CONSTRAINT_NAME) +'];' + CHAR(13)
  FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT i1.TABLE_NAME, i2.COLUMN_NAME
              FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
             INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

EXEC (@SQL)

PRINT @SQL

Friday, 24 October 2014

Search within range with LINQ and DbGeography

    var myLocation = DbGeography.FromText(string.Format("POINT({0} {1})", lon, lat)); 
    var result = (from u in _db.Restaurants
           orderby u.Location.Distance(myLocation)
           where u.Location.Distance(myLocation) < distance
           select u).Take(limit).ToList();
distance is a double and its value is in meters.

Wednesday, 22 October 2014

Przechowywanie datasource pomiędzy PostBack

        private string _countriesList = "countries";
        private List<CountryInfo> _countries;
        private List<CountryInfo> Countries
        {
            get
            {
                if (ViewState[_countriesList] == null)
                    return new List<CountryInfo>();
                return (List<CountryInfo>)ViewState[_countriesList];
            }
            set
            {
                ViewState[_countriesList] = value;
                _countries = value;
            }

        }

Monday, 25 November 2013

Don't use SPList.Items, use GetItems() instead

private static void GetItemsFromList()
{
    //from MDSN: It is best practice is to use one of the GetItem* methods of SPList to return a filtered collection of items.

    using (SPSite site = new SPSite(webUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.GetList(ListUrl);  //my list has 2 items
            Console.WriteLine(list.ItemCount);   //returns 2
            Console.WriteLine(list.Items.Count); //returns 0

            foreach (SPListItem item in list.Items)
            {
                // will not go inside loop, because list.Items is empty
            }

            for (int i = 0; i < list.ItemCount; i++)
            {
                var item = list.Items[i];  //will cause ArgumentOutOfRangeException
            }

            var items = list.GetItems(new SPQuery());  //returns all items
        }
    }
}

Monday, 29 July 2013

SharePoint social feed - how to get mentions

The article on MSDN is good starting point [1]. It shows example on how to get feed manager, make asynchronous call and retrieve newsfeed.

Instead of retrieving newsfeed, let's retrieve mentions. For this use getMentions() method[2].

In original code, while iterating, all non-normal threads were ignored. Here instead, only thread type 3 will be used [3].
Original code retrieved Text property from Thread [4]. For mentions, that would always render something like "Mentioned by John Doe". We need to go deeper in thread's properties to get actual mention text. See code example below.

Another challenge is to get URL of story. I could not find this in documentation, but was able to reverse engineer this property from raw object.
var url = thread.$2c_1;
In the end, text and url were pushed into array, so I can work with it in later and display for user in any form that is convenient.
        var mentionsArray = [];
        var mentionsCount;
        // Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
        SP.SOD.executeOrDelayUntilScriptLoaded(GetFeeds, 'SP.UserProfiles.js');

        // Declare global variables.
        var clientContext;
        var feedManager;
        var mentionsFeed;

        function GetFeeds() {

            // Initialize the current client context and the SocialFeedManager instance.
            clientContext = SP.ClientContext.get_current();
            feedManager = new SP.Social.SocialFeedManager(clientContext);

            // Set parameters for the feed content that you want to retrieve.
            var feedOptions = new SP.Social.SocialFeedOptions();
            feedOptions.set_maxThreadCount(10); // default is 20

            // Change the sort order to optimize the Timeline feed results.
            feedOptions.set_sortOrder(SP.Social.SocialFeedSortOrder.byCreatedTime);
            mentionsFeed = feedManager.getMentions(false, feedOptions);     //do not clear unread mentions

            clientContext.load(feedManager);
            clientContext.executeQueryAsync(CallIterateFunctionForFeeds, RequestFailed);
        }
       function CallIterateFunctionForFeeds() {
            IterateThroughFeed(mentionsFeed);

            // Later mentionsArray will be boud by using Knockout.js ;)
            var viewModel = new AppViewModel();
            ko.applyBindings(viewModel);
        }
        function IterateThroughFeed(feed) {
            var feedOwner = feedManager.get_owner().get_name();

            // Iterate through the array of threads in the feed.
            var threads = feed.get_threads();
            mentionsCount = feed.get_unreadMentionCount();

            for (var i = 0; i < threads.length ; i++) {
                var thread = threads[i];
                var actors = thread.get_actors();

                // Use mentions. (SocialThreadType.mentionReference)
                if (thread.get_threadType() == 3) {

                    // Get the root post's author, content, and number of replies.
                    var post = thread.get_rootPost();
                    var authorName = actors[post.get_authorIndex()].get_name();
                    var postContent = post.get_text();
                    var postReference = thread.get_postReference();
                    var referencedPost = postReference.get_post();
                    var mentionText = referencedPost.get_text();

                    var url = thread.$2c_1;         //reverse engineered this name

                    mentionsArray.push({ text: postContent + " " + mentionText, url: url });
                }
            }
        }
        function RequestFailed(sender, args) {
            //not implemented
        }
MSDN Articles:
[1] Retrieve social feeds by using the SharePoint 2013 JavaScript object model http://msdn.microsoft.com/en-us/library/jj164025.aspx#bkmk_GetFeeds
[2] SP.Social.SocialFeedManager.getMentions Method http://msdn.microsoft.com/en-us/library/jj679814.aspx

Friday, 5 April 2013

Animated tile-style hyperlinks

I must admit, I begin to love jQuery. I am not JavaScript developer, yet jQuery is so easy, that even I can use it.

In this post I will explain how to create animated, scrollable box with alternating links and images. Just like this one:


1.       Start by adding these scripts inside body of your page:

    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.cycle/2.88/jquery.cycle.all.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.18/jquery-ui.min.js" type="text/javascript"></script>
   <script type="text/javascript">

        $(document).ready(function () {
            var randomDelay = function () {
                var min = 1000;
                var max = 1500;
                var wait = Math.round(Math.random() * (max - min) + min);

                return wait;
            };

            $('.animated-tile').cycle({
                fx: 'scrollDown',
                easing: 'easeOutBounce',
                speed: 3000,
                delay: -3000,
                timeoutFn: randomDelay,
                random: 0,
                pause: 1,
            });
        });

    </script>

Here, in randomDelay function, set minimum and maximum time in milliseconds.

2.      Put div section where the box will be:
<div class="animated-tile" style="position: relative; width: 110px; height: 110px; overflow: hidden;">
Width and height should be the same as dimensions of images to cycle.

3.       Put multiple links with images inside. That's it!
<a href="http://goleszympansy.pl>
   <img src="myimage.jpg" height="110px" width="110px" border="0px">
</a>