Header

Tuesday, 9 July 2024

CSS Styling

Make a box with rounded corners:

You can see that the box has a rounded corner, which we can do by using the CSS code below. In this case, "box" is the class name for the div.

.box {
height: 120px;
width: 120px;
background-color: #06d590;
color: black;
border-radius: 15px;
}

Create a box with a shadow effect using only CSS:

You can see that the box has a shadow effect, which we can do by using the CSS code below. In this case, "boxShadow" is the class name for the div.

.boxShadow {
height: 120px;
width: 120px;
background-color: #cf6a22;
color: black;
box-shadow: 10px 10px 18px 0px #808080;
}

Box shadows take five values and are applied to the outside portion of tags by default. first value for the X index, second value for the Y index, third value for the blur option, fourth value for the spread, and last value for the shadow's color

Create a box with a Linear Gradient using only CSS:


You can see that the box has a linear background color, which we can do by using the CSS code below. In this case, "boxLinearGradient" is the class name for the div.

.boxLinearGradient {
height: 120px;
width: 120px;
background:linear-gradient(blue, #cf6a22,green);// Default it put color from top to bottom
background:linear-gradient(to right,blue, #cf6a22,green);// This will start color from right
background:linear-gradient(to left,blue, #cf6a22,green);// This will start color from left
background:linear-gradient(45deg,blue, #cf6a22,green);// This will rotate the color with 45deg
color: black;
}

Multiple colors are added to the background using a linear gradient. By default, the order is top to bottom. We are also able to adjust the order to "left," "right," and "60 degrees."

Using text shadow in CSS, create a text shadow:

Text shadow effect

You can see that the text shadow effect , which we can do by using the CSS code below. In this case, "Shadoweffect"is the class name for the div.

.Shadoweffect
color: white;
text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;


Using loader in CSS, create a loader:

You can see the loader , which we can do by using the CSS code below. In this case, "loader"is the class name for the div.

.loader {
width: 50px;
height: 50px;
border-radius: 50%;
border: 10px solid white;
border-top: 10px solid blue;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}


Using filter: drop-shadow in CSS, create a image shadow:

You can see that the image shadow , which we can do by using the CSS code below. In this case, "image"is the class name.

.image{
width: 100px;
filter: drop-shadow(10px 10px 2px #1a1a1a)!important;
}
.image>img{
width: 100%;
border: none;
background:none;
}


Using this code to ensure that the image size will always fit within the div even if the div size changes.

You can see the image that we were able to create with the CSS code below."Photo" is the class name in this instance.

.photo{
height: 100px;
width: 150px;
display: flex;
justify-content: center;
align-items: center;
}
.photo>img{
width: 100%;
height: 100%;
background: none;
border: none;
}

Saturday, 6 July 2024

What is State in React

What is State in React?

State of a component is an object that holds some information that may change over the lifetime of the component. The important point is whenever the state object changes, the component re-render

Lets take an example of User component with message state.
Here useState hook has been used to add state to the User component and it return array with current state and function to update it.

Declare state in the function component

  import React ,{useState} from "react";
  function User(){
  const [message,setMessage]=useState("welcome to React world");
  return(
  <h1>{message}<h1/>
  );
  }

Declare state in the class component

  import react from 'react';
  class User extends React component {
  constructor (props){
  supper(props);
  this state={
  message:"welcome to React world",
  };
  }
 render(){
  return(
  <h1>{this.state.message}<h1/>
 );
  }
  }

State is similar to props,but it is private and fully controlled by the component. It is not accessible to any other component till the owner component decides to pass it.

What is Props in React

Props are input to Component. It can be single value or objects, containing a set of values that are passed to components on creation, similar to HTML tag attributes.
The primary purpose of props in React is to provide following component functionality.

  • Pass custom data to your component
  • Trigger state changes

This reactProps(or whatever you come up with) attributes name then becomes a property attached to React's native "props" object which originally already exists on all components created using React library
//props.reactProps

Functional Component

import React from "react";
import ReactDom from "react-dom";
const ChildComponent =(props)=>{
return(
<div>
<p>{props.name}</p>
<p>{props.age}</p>
</div>
);
};

const ParentComponent =(props)=>{
return(
<div>
<ChildComponent name="jo" age="30"/>
<ChildComponent name="So" age="29"/>
</div>
);
};

Class Component

import React from "react";
import ReactDom from "react-dom";
class ChildComponent extends React.Component{
render(){
return(
<div>
<p>{this.props.name}</p>
<p>{this.props.age}</p>
</div>
);
}
}

Friday, 5 July 2024

React Tutorial

What is React?

React is an open-source front-end JavaScript library that's utilized for building component bassed client application

  • React is especially used for Single page application
  • It is used for handling View layer of Web Application and Mobile app.
  • React Uses JSX syntax. JSX is as syntax extension of JS that allow developers to write HTML in their JS Code
  • React uses Virtual Dom instead of Real DOM.
  • Real DOM manipulation are expensive.
  • React uses reusable UI Components to develop the view.

What is JSX?

JSX stands for JavaScript XML and it is an XML-Like extension to ECMA Script. Basically it provide the syntax for the Below Function.

React.createElement(type, props,... children)

In the below example the text inside <h1> tag is returned as JavaScript function to render function.

export default function App(){
return(
    <h1>{"Hello this is JSX code!"} </h1>
  );
 }

If you don't use JSX syntax then the respective JavaScript code should be written as below.

Functional Component

  import {createElement} from 'react';
  export default function App(){
     return createElement(
      'h1',
      {
     className:'greeting'},
      'Hello, This is a JSx Code'
    );
  }

Class Component

  class App extend React.Component{
     render(){
      return(
     <h1>"{Hello, This is a JSx Code}</h1>
    );
  }
 }

Tuesday, 2 May 2023

Read cookie using JavaScript Code

Read cookie using JavaScript Code

Today, we'll look at how to use JavaScript code to read cookies. The function readCookie, which is located below, accepts a cookie's name and returns its value.

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++)
    {
     var c = ca[i];
     while (c.charAt(0)==' ')
     {
      c = c.substring(1,c.length);
     }
    if (c.indexOf(nameEQ) == 0)
     return c.substring(nameEQ.length,c.length);
    }
  return null;
}

I will demonstrate how to generate cookies using JavaScript in the code below.

function cookieCheck(){
  var interval;
  if(readCookie("userlogTime") == null)
  {
   var cDateTime = new Date();
   var timeSet = cDateTime.getHours();
   document.cookie ="userlogTime="+timeSet;
   }
  }
The above code show how we can create cookie using javascript

Deferred in SharePoint JSON

How to use Deferred in SharePoint JSOM?

I'll demonstrate how to utilize Deferred in SharePoint Online today.
All functions in SharePoint operate asynchronously, however occasionally we must call a function after another has finished. Assuming we have two lists and must retrieve data sequentially from each, delayed is used in this scenario

Swap value of two variables without using 3rd variable

How to swap two variable without using 3rd variable?

Hi Friends.
Today we will see how we can swap value of two variable without using the third variable.
For that will perform the below steps.
Step 1. Declare both variables.
  var x=13;
  var y=21;
Step 2. Add both variable and assign to the first variable.
  x=x+y; //13+21, x =34

Step 3. Subtract second variable from first variable as it contains the sum of both variables and assign to the second variable. By doing this, second variable will hold the value of first variable value which was assign in the beginning.

  y=x-y; //34-21, y=13

Step 4. Now subtract second variable from first variable as it contains the sum of both variables and assign to the first variable. By doing this, first variable will hold the value of second variable value which was assign in the beginning.

   x=x-y; //34-13. x=21
Complete code:-
  var x=13;
  var y=21;
  x=x+y; //13+21, x =34
  y=x-y; //34-21, y=13
  x=x-y; //34-13. x=21

File upload and overwrite into the SharePoint library using JavaScript

 Hi Friends,

We will see how we can upload file into the SharPoint library and also overwrite, if the file is present into the library.

We can use the below code to upload the file into the SharePoint document library.

Also we can overwrite the file if already present into the Document library.

By default, it does not allow to overwrite the file but through the code we can set overwrite true.

set_overwrite(true);

  <script language="javascript" type="text/javascript">

        var fileInput;
        $(document).ready(function () {

                fileInput = $("#getFile");
                SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);

            });

        function registerClick() {
            //Register File Upload Click Event   
            $("#addFileButton").click(readFile);
        }

        var arrayBuffer;

        function readFile() {

            //Get File Input Control and read the file name  
            var element = document.getElementById("getFile");
            var file = element.files[0];
            var parts = element.value.split("\\");
            var fileName = parts[parts.length - 1];

            //Read File contents using file reader  

            var reader = new FileReader();
            reader.onload = function (e) {
                uploadFile(e.target.result, fileName);
            }
            reader.onerror = function (e) {
                alert(e.target.error);
            }

            reader.readAsArrayBuffer(file);
        }

        var attachmentFiles;

        function uploadFile(arrayBuffer, fileName) {
            //Get Client Context,Web and List object.  
            var clientContext = new SP.ClientContext();
            var oWeb = clientContext.get_web();
            var oList = oWeb.get_lists().getByTitle('Documents');

            //Convert the file contents into base64 data  
            var bytes = new Uint8Array(arrayBuffer);
            var i, length, out = '';
            for (i = 0, length = bytes.length; i < length; i += 1) {
                out += String.fromCharCode(bytes[i]);
            }
            var base64 = btoa(out);

            //Create FileCreationInformation object using the read file data  
            var createInfo = new SP.FileCreationInformation();
            createInfo.set_content(base64);
            createInfo.set_overwrite(true);
            createInfo.set_url(fileName);

            //Add the file to the library  

            newFile = oList.get_rootFolder().get_files().add(createInfo);
            var myListItem = newFile.get_listItemAllFields();
            myListItem.set_item("PID", "33")

            //Load client context and execcute the batch  
            myListItem.update();
            clientContext.load(newFile);
            clientContext.executeQueryAsync(QuerySuccess, QueryFailure)
        }

        function QuerySuccess() {

            console.log('File Uploaded Successfully.');
            alert("File Uploaded Successfully.")
        }

        function QueryFailure(sender, args) {

            console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
            alert("Request failed with error message - " + args.get_message() + " . Stack Trace - " + args.get_stackTrace());

        }


    </script>



Monday, 1 May 2023

How to prevent to fire parent click in jQuery/JavaScript

Hi Friends,
Today we will see how we can prevent parent click event when end user clicks on child. 

Some time it happens that we have associated click event of parent DOM element and also on click of Child DOM element. In this situation if end user clicks on Child element, then both events will be triggered. But our requirement is not firing Parent event on clicking on child element. 
<html>
    <head>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"
  integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="
  crossorigin="anonymous"></script>
  <script>
    $(document).ready(function() {
    $(".parent").on('click',function(e){
        alert("You have called Dad");
    });
    $(".child").on('click',function(e){
          alert("You have called son");
    });
});
  </script>
    </head>
    <body>
        <div class="parent">
            <div class="child">Child where event has been added</div>
            <div>Child where no event has added </div>
        </div>
    </body>
</html>

If you run above code, it will show you two alerts on clicking on Child element. 
To resolve this issue, we will use e.stopPropagation();
This small line of code will solve the problem. 


<html>
    <head>
<script
  src="https://code.jquery.com/jquery-3.6.4.min.js"
  integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="
  crossorigin="anonymous"></script>
  <script>
    $(document).ready(function() {
    $(".parent").on('click',function(e){
        alert("You have called Dad");
    });
    $(".child").on('click',function(e){
        e.stopPropagation();
        alert("You have called son");
    });
});
  </script>
    </head>
    <body>
        <div class="parent">
            <div class="child">Child where event has been added</div>
            <div>Child where no event has added </div>
        </div>
    </body>
</html>











Sunday, 14 July 2013

Get Data of current login user in Sharpoint




Get Data of current login user in Sharpoint
some time we need to get data according to current user.
Like items that has been created by current login user.

And there so many approach to do this but,
what I will recommend that never goes wrong.

  osb.Append("     <Where>")
  osb.Append("       <Eq>")
  osb.Append("        <FieldRef Name=""Author"" LookupId=""True"" />")
  osb.Append("        <Value Type=""Lookup""   >" &
                        SPContext.Current.Web.CurrentUser.ID & "</Value>")
  osb.Append("      </Eq>")
  osb.Append("   </Where>")


Just add this query and get what you wanted :D

How to get Site, Web, and List name from a list url

How to get Site, Web, and List name from a list url

Some time we have url of list and need to find its web, list name ...

Basically, we need to split string and get web name and list.
 
We have SharPoint to do this in easy way and also dynamic... :)

 Using siteCollection As New SPSite(listurlfromitems)
            Dim Site As SPSite = siteCollection
            Dim myWeb As SPWeb = siteCollection.OpenWeb()
            Dim _list As SPList = myWeb.GetList(listurlfromitems)
End Using

Here listurlfromitems is a string which holds URL of list
after that we can find site, web, and list in Site, myWeb, _list variable

 

Thursday, 8 November 2012

How to copy files between two SiteCollection


Public Function MoveListItemsSiteToSite(sourceSiteURL As String, sourceList As String, destinationSiteURL As String, destinationList As String, retainMeta As Boolean) As Boolean
        Using sourceSite As New SPSite(sourceSiteURL)
            Using sourceWeb As SPWeb = sourceSite.OpenWeb()
                sourceWeb.AllowUnsafeUpdates = True
                ' Get your source library
                Dim source As SPList = sourceWeb.Lists(sourceList)
                ' Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset
                Dim items As SPListItemCollection = source.Items
                Dim fileCount As Integer = 0
                Using destSite = New SPSite(destinationSiteURL)
                    Using destinationWeb = destSite.OpenWeb()
                        destinationWeb.AllowUnsafeUpdates = True
                        ' get destination library
                        Dim destination As SPList = destinationWeb.Lists(destinationList)
                        ' Get the root folder of the destination we'll use this to add the files
                        Dim destinationFolder As SPFolder = destinationWeb.GetFolder(destination.RootFolder.Url)
                        ' Now to move the files and the metadata
                        For Each item As SPListItem In items
                            'Get the file associated with the item
                            Dim file As SPFile = item.File
                            ' Create a new file in the destination library with the same properties
                            Dim newFile As SPFile = destinationFolder.Files.Add(destinationFolder.Url + "/" + file.Name, file.OpenBinary(), file.Properties, True)
                            If retainMeta Then
                                Dim newItem As SPListItem = newFile.Item
                                WriteFileMetaDataFiletoFile(item, newItem)
                            End If
                            file.Delete()
                            fileCount += 1
                        Next
                        destinationWeb.AllowUnsafeUpdates = False
                    End Using
                End Using
                sourceWeb.AllowUnsafeUpdates = False
                Return True
            End Using
        End Using
    End Function
    Public Shared Sub WriteFileMetaDataFiletoFile(sourceItem As SPListItem, destinationItem As SPListItem)
        destinationItem("Editor") = sourceItem("Editor")
        destinationItem("Modified") = sourceItem("Modified")
        destinationItem("Modified By") = sourceItem("Modified By")
        destinationItem("Author") = sourceItem("Author")
        destinationItem("Created") = sourceItem("Created")
        destinationItem("Created By") = sourceItem("Created By")
        destinationItem.UpdateOverwriteVersion()
    End Sub

Friday, 26 October 2012

find checked radio button throug jQuery

$("#_chkbox").change(function () {
            var items = $(".childCheckBox").find("input");
            if ($('#_chkbox').is(':checked') == false) {
                for (i = 0; i < items.length; i++) {
                    if (items[i].type == "checkbox") {
                        items[i].checked = false;
                    }
                }
            }
            if ($('#_chkbox').is(':checked') == true) {
                for (i = 0; i < items.length; i++) {
                    if (items[i].type == "checkbox") {
                        items[i].checked = true;
                    }
                }
            }
        });

Wednesday, 3 October 2012

Generate CSV File in ASP.Net



 Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Response.Clear()
        Response.ContentType = "text/csv"
        Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}.csv", DateTime.Now))
        Dim _web As SPWeb = New SPSite(SPContext.Current.Site.Url).OpenWeb()
        Dim _list As SPList = _web.Lists("List Name")
        Dim _items As SPListItemCollection = _list.Items
        For Each _item As SPListItem In _items
            Response.Write(_item("Title") + "," + CStr(_item("ID")) + "," + System.Environment.NewLine)
        Next
        Context.Response.End()
    End Sub

Wednesday, 26 September 2012

How to check id of clicked button

Hi Frnds,

Today i m trying to share with you one interesting things... like how can we find "who is responsible for postback ?" 

very easily w to catch target controls who fired postback event.

Take a look of this code.


Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        MyBase.OnLoad(e)
        If Page.Request.Params("__EVENTTARGET") = btnClikOk.UniqueID Then
            txtResult.Text = "Ok Button has clicked"
        End If
        If Page.Request.Params("__EVENTTARGET") = Button1.UniqueID Then
            txtResult.Text = "Cancel button has clicked"
        End If
End Sub

Page.Request.Params("__EVENTTARGET") this one will return target control ID and by condition checking you can catch Control.

Don't you think this is very simple ?



Friday, 21 September 2012

Modal Dailog Box In SharePoint

Modal dialog play very important role to improve the user experience by reducing the number of postbacks. So, SharePoint 2010 comes up with in-build API to show modal dialog to improve the user experience. Here, I will explain you How to integrate SharePoint 2010 modal dialog with the application and some real time problems and their solutions. Before I go on and provide you with the details, Let us see some of the features that this new Modal Dialog provides.

Functionality provided by Modal Dialog: -
       - Display HTML content  in Modal Dialog
       - Display external url (e.g. http://www.google.com) or any application page of SharePoint in the form of an iframe
       - Show/Hide Close button
       - Show/Hide Maximize button

Mentioned below are the steps to integrate a modal dialog in the SharePoint 2010:
  1. The JavaScript files for the ECMAScript Object Model (SP.js, SP.Core.js, SP.Ribbon.js, and SP.Runtime.js ) are installed in the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS directory. We need to add these JavaScript files in the page.
  2. To open a dialog we need to use the 'SP.UI.ModalDialog.showModalDialog' method from the ECMAScript Client Object model and we can pass following parameters as per requirement:
width: Set the width of the modal dialog
height: Set the height of the modal dialog
html: the ID HTML control or HTML content to be displayed in modal dialog
url: Page url or relative path
dialogReturnValueCallback: In case we want some code to run after the dialog is closed, set JavaScript method name
allowMaximize: Set to true or false to show hide this option.
showClose: Set to true or false to show or hide the close button

Examples:
a. Sample code to show HTML content in the SharePoint 2010 modal dialog:

HTML code

// Modal Dialog HTML content

<div id="divModalDialogContent">
        Hello World!
        <input type="button" value="OK"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, 'Ok clicked'); return false;"
            class="ms-ButtonHeightWidth" />
        <input type="button" value="Cancel"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancel clicked'); return false;"
            class="ms-ButtonHeightWidth" />
</div>


JavaScript Code
<script type="text/javascript">
       // Call openDialog method on button click or on page load  
       function openDialog() {
            var options = {
                html: divModalDialogContent,  // ID of the HTML tag
                                              // or HTML content to be displayed in modal dialog
                width: 600,
                height: 300,
                title: "My First Modal Dialog",
                dialogReturnValueCallback: dialogCallbackMethod,  // custom callback function
                allowMaximize: true,
                showClose: true
            };
            SP.UI.ModalDialog.showModalDialog(options);
        }
        //Results displayed if 'OK' or 'Cancel' button is clicked if the html content has 'OK' and 'Cancel' buttons
        function onDialogClose(dialogResult, returnValue) {
            if (dialogResult == SP.UI.DialogResult.OK) {
                alert('Ok!');
            }
            if (dialogResult == SP.UI.DialogResult.cancel) {
                alert('Cancel');
            }
        }
        // Custom callback function after the dialog is closed
        function dialogCallbackMethod() {
            alert('Callback method of modal dialog!');
        }
</script>


         b. Sample code to open a web page or application page in the modal dialog: 

JavaScript code
<script type="text/javascript">
    function openDialog() {
        var options = {
            url: "<Page Url>",
            width: 600,
            height: 300,
            title: "My First Modal Dialog",
        };
        SP.UI.ModalDialog.showModalDialog(options);
    }
</script>



Mentioned below are real time scenarios, you may encounter while using out of box modal dialog of SharePoint 2010 :-
1. Scenario: If page is too long and with the movement of vertical scrollbar, modal popup also move with the scrollbar. Ideally position of modal dialog should be fix.

Solution: Put mentioned below CSS class in you page:
.ms-dlgContent
{
   positionfixed!important;
}
2. Scenario: Display modal popup on page load depending. Sometimes the page don't show modal dialog and a JavaScript error message comes (error: showModalDialog does not exist in SP.UI.ModalDialog).

Solution:  Use following code- ExecuteOrDelayUntilScriptLoaded(<showModelMethodName>, "sp.js"); 
              This method be make sure that js method 
showModalDialog is not called till sp.js is fully loaded.


3. Scenario: Sometime we need to close popup from server side and also parent window refresh is required after saving modal dialog data in the SharePoint.

Solution: Mentioned below is the sample code to implement above requirement-

a.  Check current page is popup page or not

//Custom list or library form New, Edit or Display
if(SPContext.Current.IsPopUI)
{
      // Code  
}

OR
//Layout pages you can ensure byquery string
if(Request.QueryString["IsDlg"]=="1")
{
        //code
}




b. To close popup use mentioned below JavaScript code:
<script type="text/javascript">
        //Close popup on cancel button click
        function CloseForm() {
            window.frameElement.cancelPopUp();
            return false;
        }
        //Commit/Refresh parent window on save button click
        function SaveForm() {
            window.frameElement.commitPopup();
            return false;
        }
</script>

c. use following server side code to close or save modal dialog:

//Put following code in the button click event, if update panel is not present in the page
ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(),"CloseForm()"true);
OR
// Put following code in the button click event, if update panel is present in the page
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), Guid.NewGuid().ToString(),"CloseForm()"true);



4. Scenario: After closing modal dialog, all controls disappear from the page.
Solution: If you assign HTML element id like we have done in our first example, you might encounter this issue, we should set copy of modal data instead of assigning ID. See sample code below:

<script type="text/javascript">
    //Pass copy of HTML content instead of content control ID
    function openDialog() {
        var cloneModalContent = document.createElement('div');
        cloneModalContent.innerHTML = document.getElementById('divModalDialogContent').innerHTML;
        var options = {
            html: cloneModalContent, //html content to be displayed in modal dialog
            width: 600,
            height: 300,
            title: "My First Modal Dialog",
            dialogReturnValueCallback: customOnDialogClose, //custom callback function
            allowMaximize: true,
            showClose: true
        };
        SP.UI.ModalDialog.showModalDialog(options);
    }
</script>