rest – HTML Page not caching

I already checked my local browser settings and nothing is stopping caching (I see several other network requests in the same page load that cache successfully). Whenever I navigate away from the page and back, this resource always loads (and takes a second or two to do so). It doesn’t appear to be using the cache at all. Here are my headers:

General

Request URL: https://example.website.stage/htmlpage/
Request Method: GET
Status Code: 200 
Remote Address: ~omitted~
Referrer Policy: strict-origin-when-cross-origin

Response Headers

alt-svc: clear
cache-control: public, max-age=43200, immutable
content-length: 68988
content-security-policy: frame-ancestors 'self'
content-type: text/html; charset=utf-8
date: Fri, 05 Mar 2021 17:01:55 GMT
server: istio-envoy
set-cookie: session_timer=session_timer; Expires=Fri, 05-Mar-2021 17:16:55 GMT; Secure; Path=/
strict-transport-security: max-age=31536000; includeSubDomains
vary: Cookie
via: 1.1 google
x-content-type-options: nosniff
x-envoy-upstream-service-time: 2618
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block

Request Headers

:authority: example.website.stage
:method: GET
:path: /htmlpage/
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cookie: ~omitted~
referer: https://example.website.stage/htmlpage
sec-ch-ua: "Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-fetch-dest: document
sec-fetch-mode: navigate
sec-fetch-site: same-origin
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36

javascript – Update textField to first letter capital and rest lower case

Is there an option via JavaScript to say: if the FirstName textfield is not null then update the text so that it is 1st letter being capital and the remaining lower case?

For example somebody types in the FistName textfield: jOHN (accidently).
This is how then the data is stored in SharePoint list, and I would like so that a java script updates the written text into the correct format before it is stored wrongly in the SP list.

I am trying something like this:

    NWF$(document).ready(function () {
    NWF$("#" + txtFirstName).change(function () {
        
        // get the text value from the FirstNname textfield
        var textContent = NWF$("https://sharepoint.stackexchange.com/#" + txtFirstName).text();

        // check to see if the value is not null
        if (textContent.length > 0) {

            // format the first letter to UpperCase and the rest to LowerCase
            textContent = NWF$("#" + txtFirstName).toUpperCase() + txtFirstName.substr(1).toLowerCase();
            this.value = txtFirstName;
        }
      });
    });

node.js – uncaughtException: write EPIPE error API REST com typeorm e typescript

Recentemente decidi aprender SOLID e desde então venho tentado fazer uma API rest usando typescript e typeorm, mas está acontencendo um erro que não consigo resolver ele exibe o seguinte erro:

print error in terminal

Este erro só aparece quando importo uma classe chamada CreateUserRepository mas quando a tiro o erro some, essa é a classe:

    import { ICreateUserRequestDTO } from '@modules/users/dtos/CreateUserDTO';
    import { IUserRepository } from '@modules/users/repositories/IUserRepository';
    import { getRepository, Repository } from 'typeorm';
    import User from '../entities/User';
    
    class CreateUserRepository implements IUserRepository {
      private ormRepository: Repository<User>;
    
      constructor() {
        this.ormRepository = getRepository(User);
      }
    
      public async create(user: ICreateUserRequestDTO): Promise<User> {
        const newUser = this.ormRepository.create(user);
    
        await this.ormRepository.save(newUser);
    
        return newUser;
      }
    }
    
    export default CreateUserRepository;

Enfim, já pesquisei na internet e não obtive sucesso com os resultados e sinceramente não sei mais como resolver

project online rest api date fields

That’s probably the raw milliseconds.

Dates are actually stored as numbers that represent ticks of a certain size from a certain starting point.

From the MDN documentation on JavaScript dates:

A JavaScript date is fundamentally specified as the number of
milliseconds that have elapsed since midnight on January 1, 1970, UTC.

And it then goes on to point out the difference between JavaScript dates and UNIX time stamps, and that in UNIX the tick is a full second (not millisecond):

This date and time are not the same as the UNIX epoch (the number of
seconds that have elapsed since midnight on January 1, 1970, UTC),
which is the predominant base value for computer-recorded date and
time values.

And, in the C# DateTime struct, the ticks are 100 nanoseconds, and are counted since 12:00 midnight on Jan 1, 0001 AD.

So there are some differences. Why would I assume the ones coming from the Project Online REST API are in milliseconds?

Well, for one, Date(<something>) looks a heck of a lot like the JavaScript Date constructor. And, in addition to using an ISO string ("2021-02-10T08:00:00.000Z") or a short date format string ("2/10/2021"), you can use a number representing milliseconds since Jan 1 1970 in the Date constructor.

Second, I am also assuming that you are sending a header of Accept: application/json along with your REST request, which is telling Project Online that you want your response in JavaScript Object Notation, which is a pretty big clue to Project Online that you are using JavaScript, so it might format a response it’s going to send in JSON in a JavaScript-friendly way.

And third, it’s Project Online, and a heck of a lot of modern development, especially revolving around using cloud services/APIs, is very client-side oriented, meaning, done in JavaScript. So they could be leaning heavily on that expectation as well.

That’s all speculation though. I really am just guessing that it’s milliseconds (based on those hunches).

A quick test to see if that’s right? Open up a browser console, and just try it out:

// doing this
new Date(1612944000000)

// outputs
Wed Feb 10 2021 03:00:00 GMT-0500 (Eastern Standard Time)

At least, that’s what I get in my time zone. Does that date and time make sense for what you are expecting?

As far as why there is a difference between how REST API date results are formatted for the Project Online API vs. the SharePoint API, I guess that’s a question for the Microsoft development teams…

(As a side note – I haven’t worked with Project Online. I have worked with Project Server 2016 on-prem, and results from the /ProjectData/ REST API in that version do come back as ISO strings, same as from SharePoint, at least if you are looking at things like TaskFinishDate, TaskBaselineFinishDate, etc..)

rest – One API endpoint for each frontend “need”

The appropriate development depends on your needs. There are two main considerations here:

Development time vs bandwidth

Would you rather waste a bit of bandwidth in favor of speeding up development? Then only develop the full order details endpoint.

Do you want to save bandwidth no matter the cost to development time? Then create an endpoint for each specific subset of order data you need.

Do you want to find a happy balance? Then only develop a few of those endpoints, e.g. a “simple” and “detailed” endpoint. Any view that is “somewhat detailed” will then waste a bit of bandwidth but any view that only needs a simple listing won’t. From experience, this usually covers most bases and finds a happy medium.

Backend-driven vs frontend-driven

Does the backend exist to serve the frontend? Or if the backend the main product, and the frontend consumes it? Depending on which is your main project, you make these kinds of decisions differently.

Personally, I consider a backend (especially a REST api) as being a project that defines its own exists, regardless of how a frontend may choose to consume it or not. This means that I don’t write custom backend endpoints that serve one specific view from one specific frontend. The backend simply provides the information, and I don’t add/change endpoints just because I decided to add/change a single field on a certain page.

But I am a backend developer and I work in companies that deliver a service (i.e. REST api), not a client app.

If your main project is the client app you’re developing, and you need to squeeze for performance/bandwidth, then the added effort of altering your backend to suit the precise needs of your frontend may be desirable for you.


As always, precision takes effort, which takes time and money. Whether it’s worth it or not very much depends on how necessary it is, and how much time and budget you have available.

rest – Syncronous or Asynchronous communications

I have to design a REST interface between two system. Let’s say system A creates a project order and each project requires multiple items to be shipped by a company (System B). Every time an item is shipped, system B sends a notification to system A with an item ID, and System B sends an acknowledgement. System A keeps track of how many items are being shipped. Once system A receive all items pertaining to the order ID, it sends a final order completion notification to system B thewith the Project Order.

Should I create it as an asynchronous REST API, where every time the order is received, a synchronous response will be send, and once all items are received, the final response will be send? Or, should I just create separate interfaces, one for item level communications, and the other one for the completion notification.

I am new to the Rest world. Please ask, if I am not clear.

magento2 – REST API: Consumer is not authorized to access %resources

I’m in the middle of finishing a Magento 2 store for a client. The last I had on my to-do list, was connect Magento to their accounting software through the REST API.

However, apparently there’s some serious issue when it comes to the REST API in the Magento installation. No matter what I do I’m always given a “Consumer is not authorized to access %resources” error, such as:

{
    "message": "Consumer is not authorized to access %resources",
    "parameters": {
        "resources": "Magento_Sales::sales"
    }
}

POSTMAN Settings:enter image description here

I’m using an Access Token created through Admin > System > Integrations. The created Integration has resource access set to ALL.

System:

  • CentOS 7
  • WHM/cPanel
  • PHP 7.3.27
  • PHP Handler SuPHP
  • Magento 2.4.1
  • Webserver: Apache (port 8080)
  • Cache: Varnish (port 80)
  • SSL: Nginx as reverse proxy for SSL (port 443)

Things I’ve tried based on similar questions:

  • Change PHP handler from CGI to SuPHP (source)
  • Enable individual API resource access instead of setting to ‘ALL’ (source)
  • Tested without Varnish between client and server
  • Tested without Nginx proxy between client and server

I really can’t seem to figure out what I’m doing wrong here. Does anybody have an idea what might be causing this? An option would be to do a fresh installation, but that’d be my very last option as I’ve been working on this Magento environment (theme, thouuuusands of products, …) for many months.

PWA/Project Online – Setting Project ID dynamically with REST

I am trying to dynamically set the Project UID in an Angular app which is deployed to every subsite throughout my PWA. I need to be able to ideally, store the Project UID in a global variable which I can then use throughout the rest of the app to point to the correct REST api endpoint.

I’m struggling with how I can leverage the function for getting the current site’s Project UID which I found here (https://sharepoint.stackexchange.com/questions/224485/project-web-app-get-project-id-from-project-related-site-via-rest), to update the global variable with the Project UID to use in my app controllers. The function works, supposedly, but when I console.log(ProjectUID) I don’t get the GUID I’m expecting, instead I get a boolean ‘false’.

Any suggestions?

var ProjectUID = ExecuteOrDelayUntilScriptLoaded(getProjectUIDProperty, "sp.js");

function getProjectUIDProperty() { 
  var ctx = new SP.ClientContext.get_current(); 
  console.log(ctx);
  this.web = ctx.get_web(); 
  console.log(this.web);
  this.props =  this.web.get_allProperties(); 
  ctx.load(this.web); 
  ctx.load(this.props);                    
  ctx.executeQueryAsync(Function.createDelegate(this, gotProperty), Function.createDelegate(this, failedGettingProperty)); 
}

function gotProperty() {                
  let ProjectUID = this.props.get_item('MSPWAPROJUID');
}

function failedGettingProperty() { 
  alert('Error: ' + args.get_message());
}
console.log(ProjectUID);


  (1): https://sharepoint.stackexchange.com/questions/224485/project-web-app-get-project-id-from-project-related-site-via-rest

sharepoint online – How to EnsureUser with AD group in REST

I am trying to add AD group to SharePoint site in REST using EnsureUser but I kept getting error message “The specified user c:0+.w|S-1-5-21-1814438218-152777602-930774774-762833 could not be found“. Can someone please tell me what the correct format is for the logonName string? AD is on prem and we are using SP Online. Below is the code:

        string digest = formDigest == "" ? GetRequestDigest() : formDigest;
        string logonNameStr = WebUtility.HtmlEncode("c:0+.w|") + "S-1-5-21-1814438218-152777602-930774774-762833"; <== This seems to be incorrect
        string ensureUserUrl = _siteUrl + "_api/web/EnsureUser"; 
        
        using (var handler = GetHttpClientHandler(_siteUrl))
        {
            using (HttpClient client = GetHttpClient(handler))
            {
                client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
                var payload = new { logonName = logonNameStr };
                string jsonBody = JsonSerializer.Serialize(payload);
                using (StringContent content = new StringContent(jsonBody))
                {
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose;charset=utf-8");
                    HttpResponseMessage response = client.PostAsync(ensureUserUrl, content).Result;
                    string jsonStr = await response.Content.ReadAsStringAsync();
                    if (!response.IsSuccessStatusCode) //if adding user failed
                    {
                        throw new Exception(String.Format("Failed to add AD group {0} to SharePoint site: {1}", groupName, jsonStr));
                    }
                }               

            }
        }

rest – What is the correct terminology for the components for a CURI?

Given a curi like [auth:password_reset_confirm], what do you call the part before the colon and what do you call the part after the colon?

I have a json payload with come CURIs that look like this:

...

"_links": {
    "curis": [
        {
            "name": "auth",
            "href": "http://<IP>/documentation/auth/{rel}",
            "templated": true
        },
    ],
    "self": {
        "href": "http://<IP>/resources/api/"
    },
    "auth:password_reset_confirm": {
        "href": "http://<IP>/frontend-auth/password/reset/confirm/"
    },

...
  

Now I want to make an endpoint that serves the schemas for all the other endpoints. So for example:

http://<IP>/schemas/auth/password_reset_confim

Would be the URL for the JSON schema for the endpoint [auth:password_reset_confirm]. To create a URL template for this schema endpoint I need something like this:

http://<IP>/schemas/{curi_part_before_colon}/{curi_part_after_colon}

this looks ridiculous. So I’d like to know what these are actually called.

Note that in this document it is referred to as “the part before the colon”: https://www.w3.org/2001/sw/BestPractices/HTML/2005-10-27-CURIE