Wednesday, February 26, 2025

Displaying .cr2 Files in an Image Tag in SPFx webpart

Background

Canon RAW Image files (.cr2) contain high-quality uncompressed image data used by Canon digital cameras. Unlike standard formats such as JPEG or PNG, .cr2 files are not directly supported by HTML <img> tags, which require web-friendly formats. This presents a challenge when attempting to display .cr2 images in web applications.

The Problem

Web browsers do not natively support .cr2 files for direct rendering in <img> tags. Attempting to set the src attribute of an <img> tag to a .cr2 file will result in an unsupported file error or display nothing. This limitation makes it difficult for photographers, developers, and web applications that deal with RAW image previews.

Key Challenges

  1. File Compatibility.cr2 files need to be converted to a format that browsers can display, such as JPEG or PNG.

  2. Performance – Conversion should be efficient to prevent lag, especially for large RAW files.

  3. Client-side vs. Server-side Processing – Determining whether conversion should happen on the client (e.g., using JavaScript libraries like raw.js) or on the server.

  4. User Experience – Ensuring a seamless experience with minimal load time and preserving image quality.

Objective

To develop a solution that enables the display of .cr2 images in web applications, either through on-the-fly conversion or alternative approaches, ensuring compatibility with HTML <img> tags while maintaining efficiency and quality.

Solution: Using dcraw for On-the-Fly Conversion

One effective approach is to use dcraw to convert .cr2 files on the fly and display them as JPEG images in <img> tags. Below is a step-by-step implementation guide:

Step 1: Add dcraw as an External Source in config.json

To use dcraw in your SharePoint Framework (SPFx) web part, add it as an external dependency in your config.json file:

"externals": {
  "dcraw": {
    "path": "https://cdn.jsdelivr.net/npm/dcraw@1.0.3/dist/dcraw.min.js",
    "globalName": "dcraw"
  }
}

Step 2: Import dcraw in Your .tsx File

Next, import dcraw in your TypeScript file:

require('dcraw');

Step 3: Implement the Conversion Process

Use the following code snippet to fetch the .cr2 file, process it using dcraw, and extract a JPEG thumbnail:

const dcraw = require('dcraw');
const response = await fetch(file.url);
const blobFile = await response.blob();
const buf = await blobFile.arrayBuffer();
const uint = new Uint8Array(buf);
const thumbnail = dcraw(uint, { extractThumbnail: true });
const blobImage = new Blob([thumbnail], { type: "image/jpeg" });

Step 4: Generate a URL for the Converted Image

Once the image is converted, create a URL that can be used as the src for the <img> tag:

const urlCreator = window.URL || window.webkitURL;
const imageUrl = urlCreator.createObjectURL(blobImage);

Step 5: Bind the Image URL to the <img> Tag

Now, use the generated imageUrl in your JSX to display the image:

<img src={imageUrl} alt="CR2 Thumbnail" />

Conclusion

By leveraging dcraw, we can efficiently convert .cr2 images on the fly and display them in an <img> tag within an SPFx web part. This approach ensures compatibility with modern web applications while maintaining performance and image quality.

This solution can be further optimized by handling large .cr2 files asynchronously, caching processed images, or implementing a hybrid client-server approach for improved efficiency. Happy coding!

Wednesday, February 12, 2025

Fixing "Your Web Part Will Not Appear in the Toolbox" Issue in SPFx Workbench

 If you're working with SharePoint Framework (SPFx) and encounter the frustrating error "Your web part will not appear in the toolbox" after running gulp serve, don't worry—there’s a simple fix!

Many developers face this issue where the workbench fails to load the web part even after restarting gulp serve multiple times. When checking the browser console, you may see an error like this:

nginx
Failed to load debug manifests: Error: Script error for: https://localhost:4321/temp/manifests.js

This error indicates that the debug manifest files required to load the web part are not loading correctly.

Quick Fix for the Issue

Follow these simple steps to resolve the problem:

  1. Open a New Browser Tab

    • Copy and paste the following URL into the address bar:
      bash
      https://localhost:4321/temp/manifests.js
    • Press Enter to load the URL manually.
  2. Bypass the Browser Warning

    • Your browser might display a security warning or an error message.
    • Force the page to load (for example, in Chrome, click Advanced > Proceed to localhost (unsafe)).
    • If successful, you should see a JSON response in the browser.
  3. Refresh the Workbench

    • Go back to your SPFx workbench (https://localhost:4321/workbench) and refresh the page.
    • Your web part should now appear in the toolbox! 🎉

Why Does This Happen?

This issue occurs because the browser sometimes blocks localhost requests due to security restrictions. Manually loading the manifest file helps the browser trust the request and allows your web part to load properly.

Conclusion

Next time you face the "Your web part will not appear in the toolbox" issue in SPFx, try manually loading the manifest file before restarting gulp serve. This quick trick saves time and gets you back to development without unnecessary debugging.

Friday, November 16, 2018

Solution structure in SharePoint Framework (SPFx)

You can open the solution in the code editor like visual studio code.
Go to command prompt, Navigate to the code directory, and type code. and press enter. Your source code will be open up in Visual code.



The Solution structure consist of various folder and configuration files at the root. The primary language used is TypeScript. The code mostly uses classes, modules, and interfaces written in typescript.



Folders in the Solution

Src

Code files are stored inside this folder

Lib

It contains processed code which can be bundled and distributed
All typescript files compiled into JavaScript files are stored here

Dist

Contains final distributed files
Includes javascript bundle file

Config

Contains set of JSON file for configuration

Node_modules

Contains JavaScript modules downloaded by node.js

Typings

Contains typescript typing files for various libraries
Typing support intellisense for JavaScript Library

SharePoint

Contains the final .spapp file post execution of ‘gulp package-solution’ command

Files in Solution

Let’s assume the WebPart Name is HelloWorld

WebPart Class (HelloWorldWebPart.ts)

This defines the entry point of the webpart.

Property Type Interface (IHelloWorldWebPartProps.ts)

The interface resides in the same web part file. The web part class accepts the property type of interface. This interface is used to define our own custom properties for the web part.

WebPart Menifest (HelloWorldWebPart.menifest.json)

This file holds the metadata of webpart such as display name, description, icon, version etc.

Config.json

The configuration file contains the bundling information, the components used in the solution and entry point of the solution.

This file also records the external references (for e.g. jQuery) and its dependencies. Also, references to localization resources are stored in this file.

Deploy-azure-storage.json

This file is used while deploying the client-side web part to Azure CDN. This file contains Azure storage account details.

Package-solution.json

This file contains solution id, name and version number.

Serve.json

File where we can see on what url and port workbench will be served.

Write-menifest.js

File where we can mention where manifest file can be found.

Gulpfile.js

Defines gulp tasks to run.

Package.json

Defines JavaScript library dependencies.

Tsconfig.json

Defines settings for TypeScript compilation

Thursday, November 15, 2018

Overview of SharePoint FrameWork (SPFx)


Now we have Modern Site in SharePoint. And customization in modern pages/sites supported by SharePoint Framework.
SPFx is an Open and connected Platform. It can be entirely developed using client-side languages.

Key Features

      No Iframes
Faster rendering on the browser (all controls are rendered in normal DOM)
Runs in current user context
Controls are responsive
Give controls to access the lifecycle of the SharePoint Framework web part component (Init, render, load. Serialize, de serialize, configuration changes etc)
No dependency of underlying framework. User can choose any framework like React, Angular, Knockout and more)
Open Source Development tools are used (npm, typescript, gulp, yeoman and webpack)
Can be added both classic and modern pages
Client Side Webparts, leverage modern site frameworks
Provides Modern experience, responsiveness Out of Box
Free, Open source tool chain

      Flow of Client Side Web Part



SharePoint FrameWork (SPFx) Tool Chain




While we were developing on On-Premise (2007/2010) we were developing the Solutions (WSP). WSP contains the sets of Features, Site Definitions, assemblies etc written in c # and that get deployed on SharePoint Servers.
After that Microsoft introduced AddIns. SharePoint Addins avoided the Server deployments and change the deployment pattern. Prevented these solutions from running physically on the Web Front End servers.
After that Microsoft has introduced SharePoint Framework (SPFx). A complete client side development and these webparts can run in the context of page it means no Iframe which was the pain area with SharePoint addins, no cross domain calls on your webparts

The New Tool Chain of SharePoint FrameWork.
Tool Chain Info graphics which will tell what replaced what 






This is the development server. Earlier you ware familiar with IIS and Microsoft Visual Studio. Now you just need to install this and forget IIS and VS. You do not need to touch the node.js after installing it.



This is the replacement of your NUGET. Which you were familiar with Visual Studio while installing the things using nugget package.




A Scaffolding tool for development projects, which helps us kick-start new projects, and prescribes best practices and tools to help you stay productive. SharePoint client-side development tools include a Yeoman generator for creating new web parts. The generator provides common build tools, common boilerplate code, and a common playground web site to host web parts for testing.
It’s Same like as you were earlier doing File à New à Project à Select Template in Visual studio.



A task and build manager that provides automation for build tasks, which is like MS build.





TypeScript, React, Knockoout and many other languages can be used to develop the Web part in SharePoint Framework.




Saturday, December 16, 2017

the app for SharePoint is in an invalid state and cannot be uninstalled

Error : The app for Sharepoint is in an invalid state and cannot be uninstalled.

Error : Skipping the uninstall step because the app for SharePoint is in an invalid state and cannot be uninstalled.

Error : Error occurred in deployment step ‘Install app for SharePoint’: The provided App differs from another App with the same version and product ID.

I was having a problem with deploying my SharePoint Hosted App into my Dev SharePoint environment. Earlier version of installed app was having some issues in Removal. while i tried to remove the app got the error "Sorry, we couldn't remove the app. Click to retry"


To Fix all the issues there is one solution. Actually your timer job service got stuck due to this sharepoint is unable to remove the App.

Go to Windows Services and Restart the "Sharepoint Timer Service" once the timer service will restart then again try to remove the App or Redeploy the app again on sharepoint through Visual Studio. Now it should be working fine.


Friday, October 13, 2017

Exception occured:Microsoft.SharePoint.Client.ServerException: Cannot complete this action. Sharepoint 2013

Exception occured:Microsoft.SharePoint.Client.ServerException: Cannot complete this action. Sharepoint 2013


This issue occures usually when your server is running Out of Memory.


You can fix this issue in 2 ways.


  • Reduce the Preformance of Search Service
  • Reduce the NodeRunner.exe impact on Memory


First try to reduce the performance of Search and check if you still face this problem then go for NodeRunner changes


Reduce the Preformance of Search Service

Set-SPEnterpriseSearchService -PerformanceLevel Reduced


Reduce the NodeRunner.exe impact on Memory

The node runner application used by SharePoint 2013 preview for search related process slows down the system due to memory leak issues.

Open the config file at C:\Program Files\Microsoft Office Servers\15.0\Search\Runtime\1.0\noderunner.exe.config.

<nodeRunnerSettings memoryLimitMegabytes="0" />

NodeRunner.exe is resource hungry process. By default it's set to 0 which means it can any amount of memory. You need to fix it by giving any fixed number eg. 50,100,200 etc. This sets the cap limit for memory to be used.

Restart the Sharepoint Search Host Controller Service after this change.

Thursday, October 12, 2017

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel

Exception occured at method XXX-System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

I faced this issues while accessing the site on https and i didn't had the valid certificate. I was trying to connect the sharepoint site through a console application using the CSOM code.

This issue usually come while you don't have the valid certificate.

To solve this proble just add the below line to fix this issue.


ServicePointManager.ServerCertificateValidationCallback = new       
RemoteCertificateValidationCallback
(
   delegate { return true; }
);

Instead of doing this better to use a valid Crtificate

Tuesday, October 10, 2017

Creating SharePoint App/Addin with TypeScript

Typescript language provides strong types, interfaces, and extensible classes that bring common object oriented programming concepts and techniques into JavaScript development.

The TypeScript compiler produces a JavaScript file from a source file with a .ts extension.

Here i am starting with a very simple Sharepoint App. It's just a concept which will help to how to run your app with Typescript. No any Typescript code is involved in this.

1. Create a New Sharepoint App using visual studio ("Hello User Name App")

2. Go to the Solution Explorer Select the app solution, Do the right click on it and Select Unload       Project. Once the project is unloaded do the right click again and click on Edit Project

3. Add the below lines bofore closing of </Project> tag and Save it.

<PropertyGroup>
    <TypeScriptSourceMap>true</TypeScriptSourceMap>
  </PropertyGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" />

4. Reload the Project by doing the Right click on it.

5. Now you need to install "sharePoint.Typescript.DefinitelyTyped" and "jquery.Typescript.DefinitelyTyped". For this do the right click on the solution and Select "Manage NuGet Packages..". In the NuGet Window search for the sharePoint.Typescript.DefinitelyTyped, jquery.Typescript.DefinitelyTyped and install it.

6. Now we have all the prereqisite added with the project.

7. Expand the Solution and go in Script folder. Rename App.js with some other name and add App.ts. Copy all the script from App.js and paste it into App.ts.

8.Add these line on the App.ts file
///<reference path="typings/sharepoint/SharePoint.d.ts" />
///<reference path="typings/jquery/jquery.d.ts" />

9. Build the Project

10. Click on Show All files from the Solution Explorer. You will get App.js and App.js.map. Just include them.

11. Deploy the App

The status code of response is '500'. The status text of response is System.ServiceModel.ServiceActivationException

SharePoint 2013 Error: Unexpected response from server. The status code of response is '500'. The status text of response is System.ServiceModel.ServiceActivationException.


Usually this occures due to server is running out of Memory

You can fix it by reducing the Search service Performance or you can limit the Node runner 

Solution 1.

Reduce the Search Service Performance

PS : Set-SPEnterpriseSearchService -PerformanceLevel Reduced


If this does not solve the problem then you can opt for Solution 2.

Solution 2.

There is a configuration setting for NodeRunner.exe’s configuration file that can limit RAM usage of a single process to specific value in megabytes. his configuration file is located at: C:\Program Files\Microsoft Office Servers\15.0\Search\Runtime\1.0\noderunner.exe.config.



<!-- Settings enforced by the node runner itself. -->
  <!-- These settings can also be set using command line arguments with the same name. -->
    <nodeRunnerSettings memoryLimitMegabytes="0" />

The configuration setting is under the nodeRunnerSettings node and it’s called memoryLimitMegabytes.  Its default value is 0 (unlimited).


Set it to 50 or 100 and save the file. After that restart the Sharepoint Search Host Controller Service.


This will resolve the issue.

Note : Solution 2 is not recommended approach by Microsoft.