Header

Showing posts with label Sharepoint. Show all posts
Showing posts with label Sharepoint. Show all posts

Tuesday, 2 May 2023

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>



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

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 ?



Tuesday, 11 September 2012

How to find web parts through vb.net


Hi Friedns,

Few days ago i was asked to hide Advaced search web part through one user control's button click.

i was socked how could i find that web parts, and really i wasted too much time to doing this simple task,
bcz i didnt know how to do :(
But we should not give up till get solution :D
and i finaly get solution.

There was a webpart zone in that i added advanced search web part and my Usercontrol through smartPartwithajax features.

so both are in same webpart zone.


Now this is simpl code that we use to find advanceSearchBox

 Public Sub setTab()
        Dim _controls As ControlCollection = Me.Parent.Parent.Controls
            For Each _cde As Control In _controls
                If _cde.GetType().ToString = "Microsoft.Office.Server.Search.WebControls.AdvancedSearchBox" Then
                    Dim _webpart As WebPart = CType(_cde, WebPart)
                    _webpart.Hidden = False
                    Exit For
                End If
           Next
End Sub

Call this function on ur button click on user control u will get solution .


Thursday, 23 August 2012

How to activate SharePoint Taxonomy Fearture

In this article we will be seeing how to resolve "The Taxonomy feature (Feature ID "73EF14B1-13A9-416b-A9B5-ECECA2B0604C") has not been activated" error.

Sometimes when you try to use the Managed Metadata column type in SharePoint 2010 you may get an error saying "The Taxonomy feature (Feature ID "73EF14B1-13A9-416b-A9B5-ECECA2B0604C") has not been activated".

Activating the Taxonomy Feature using Power Shell:

    GO to Start menu.
    Go to SharePoint 2010 Management Shell and select Run as Administrator.
    In the command prompt, type each of the following commands.

    Enable-SPFeature -id 73EF14B1-13A9-416b-A9B5-ECECA2B0604C -URL http://<Server>

    <Server>- is the SharePoint server name.
    Now you have activated the Taxonomy Feature.

Activating the Taxonomy Feature using STSADM command:

    GO to Start menu.
    Go to SharePoint 2010 Management Shell and select Run as Administrator.
    In the command prompt, type each of the following commands.

    STSADM -o activatefeature -id 73EF14B1-13A9-416b-A9B5-ECECA2B0604C -url http://< Server > -force

    <Server>- is the SharePoint server name.
    Now you have activated the Taxonomy Feature.

Thursday, 17 May 2012

JavaScript to read SharePoint list items

<script type="text/javascript" style="font-size: 14px">


 $(function(){
SP.SOD.executeOrDelayUntilScriptLoaded(execClientOM, 'SP.js');

})
function execClientOM() {
alert("exe");
    context = SP.ClientContext.get_current();
alert(context);
    var list = context.get_web().get_lists().getByTitle("Programmes");
    var camlQuery = SP.CamlQuery.createAllItemsQuery();
    this.listItems = list.getItems(camlQuery);

    context.load(listItems);

    context.executeQueryAsync(ReadListItemSucceeded,
                              ReadListItemFailed);
}

function ReadListItemSucceeded(sender, args) {
    var itemsString = '';
    var enumerator = listItems.getEnumerator();

    while (enumerator.moveNext()) {
        var listItem = enumerator.get_current();
        itemsString += listItem.get_item('Title') + '\n';
    }

    alert(itemsString);
}

function ReadListItemFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' +
          args.get_stackTrace());
} </script>

Wednesday, 18 April 2012

SPGrid View Styling


If we want to put our own Styling in SPGrid View then we need to change Corev4.css, and it is not good :(

So what should we do ?

Simple just put internal style sheet, but again what should we need to change. Bcz when i had started, it was too
struglling for me. But u dont worry :)
For you i have solutions.

Suppose you need to change Heading color,Background of heading then use this.

TH .ms-vb A{
color:#4b4b4b !important;
}

above style is for the heading of SPGridView text.


.ms-listviewtable .ms-vh2{
padding:0px !important;
background:#cdcdcd;
}

above style is for the background of heading


TD Table.ms-listviewtable
{
border-collapse:separate !important;
}
TH .ms-vb
{
    padding-top:5px !important;
}
.ms-vh2 Table.ms-selectedtitle
{
    background:#cdcdcd !important;
}

above code is for background setting of heading

TR.ms-viewheadertr > TH.ms-vh2:hover
{
  background:#cdcdcd !important;
}
TR.ms-viewheadertr > TH.ms-vh:hover
{
  background:#cdcdcd !important;
}



above code is for background setting of heading Hover


I will update next part sooon

Tuesday, 27 March 2012

How to Populat a Drop-Down with List Data in Sharepoint


Some time we need to bind some column of SharePoint list to one Drop-Down.
When i had started working on SharePoint i used to bind Drop-Down with list through For Each loop, so it was time consuming and not good in programming.
Now i use simple and easy code without any loop.


       Dim ds As New DataSet()
        Dim mySite As SPSite = SPContext.Current.Site
        Dim myWeb As SPWeb = mySite.OpenWeb()
        Dim list As SPList = myWeb.Lists("ListName")
        Dim DTable_List As DataTable = list.Items.GetDataTable()
        DTable_List.TableName = "Table1"
        ds.Tables.Add(DTable_List)
        DropDownBGroup.DataSource = ds.Tables("Table1")
        DropDownBGroup.DataTextField = "FieldName"
        DropDownBGroup.DataValueField = "FieldName"
        DropDownBGroup.DataBind()
        DropDownBGroup.SelectedIndex = 0



I hope this will helpful for you,

Thanks and Regards

How to get attached file url in sharepoint

This post has moved to this link

http://unique2026.blogspot.in/2013/08/how-to-get-attached-file-url-in_7.html







Friday, 27 January 2012

How to hide ContentPlaceHolder by any user control

 This post has been moved to this link.

http://unique2026.blogspot.in/2013/08/how-to-hide-contentplaceholder-by-any.html

Tuesday, 13 December 2011

SharePoint page mode(Edit/Not Edit)


We can check page mode by this value.
If it is one then page is in edit mode.
 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
document.forms[0].elements["MSOLayout_InDesignMode"].value
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Thanks and Regards

Saturday, 3 December 2011

Insert data using SPAPI

We need to call this function for adding content in lis..
function Feedbackadd()
   {
            var regad_var = $("#regad1 option:selected").text();
            \\ Get the value from one DropDown list that id is regad1
            var sub_var = $("#sub1").attr('value'); 
           \\ Get the value from one text box that id is sub1.
            var name_var = $("#name1").attr('value');
            \\ Get the value from one text box that id is name1.
            var email_var = $("#email1").attr('value');
            \\ Get the value from one text box that id is email1.
            var msg_var = $('#textareamsg1').val();
             \\ Get the value from one text box that id is textareamsg1.
            var lists = new SPAPI_Lists('listLocationt');
            \\ Give the location of document where Feedback list is there.
            var res = lists.quickAddListItem('Feedback', { Title:sub_var, Regarding:regad_var, Subject:sub_var, Name:name_var, Email:email_var, Message:msg_var });
      
         if (res.status == 200)
            {
                alert('Thank you for Feedback.');
              }
            else
            {
                alert('Unexpected error.');
            }
          
        }


Thanks ....................:-) 

Monday, 24 October 2011

How to get User Details in sharepoint.

////////////////////////////////////////////////////////

  1. Dim user As SPUser = SPContext.Current.Web.CurrentUser

  2. Checking is current login is admin or not?

    SPContext.Current.Web.CurrentUser.IsSiteAdmin

  3. This will give, all group, which are present in current site

    SPContext.Current.Web.Groups

    This will give the group name of current user

    SPContext.Current.Web.CurrentUser.Groups

  4. Here i m getting all user and add in one DropDownList

    Dim websp As SPWeb = SPContext.Current.Site.RootWeb
    Dim users As SPUserCollection = websp.AllUsers
    For Each i As SPUser In users
    dropdownlist1.Items.Add(CStr(i.Name))




How to get connected to a site in sharepoint.

////////////////////////////////////////
How to get connected to a site in sharepoint.
////////////////////////////////////////
1)
     Dim oWebsite As SPWeb = SPContext.Current.Web
2)
     Using oWebsiteRoot As SPWeb = SPContext.Current.Site.RootWeb
                ...
     End Using
3)
     Using oWebsite As SPWeb = SPContext.Current.Site.OpenWeb("Website_URL")
  ...
      End Using
4)
      Using oSiteCollection As New SPSite("http://server_name/")
         Using oWebsite As SPWeb = oSiteCollection.OpenWeb("Website_URL")
             Using oWebsiteRoot As SPWeb = oSiteCollection.RootWeb
                  ...
             End Using
         End Using
      End Using
5)
      Dim myWeb As SPWeb = SPContext.Current.Web
      Debug.WriteLine("MyWeb lists : ")
                        For Each aList As SPList In myWeb.Lists
                              Debug.WriteLine("************************************")
                              Debug.WriteLine("list Title (Display Name): " & aList)
                              Debug.WriteLine("list Title (Display Name): " + aList.Title)
                              Debug.WriteLine("list Root Folder Name: " + aList.RootFolder.Name)
                              Debug.WriteLine("************************************")
                         Next

Thursday, 20 October 2011

Hot to get Current user name using SPAPI

 This post has been moved to this

http://unique2026.blogspot.in/2013/08/hot-to-get-current-user-name-using-spapi.html


Wednesday, 19 October 2011

How to change web parts Title Style


<style>

.ms-WPHeader TD[title^='Testing'] {
HEIGHT: 50px;
BACKGROUND: url(/HomePage-Images/announcements_1px.png);
}
.ms-WPHeader TD[title^='Testing'] SPAN:first-child {
PADDING-LEFT: 55px;
WIDTH: 65px;
PADDING-TOP: 0px;
}
.ms-WPHeader TD[title^='Testing'] H3 {
PADDING-BOTTOM: 0px;
 MARGIN: 0px;
PADDING-LEFT: 0px;
PADDING-RIGHT: 7px;
HEIGHT: 55px;
COLOR: black;
FONT-SIZE: 1.2em;
PADDING-TOP:0px;
BACKGROUND: url(/HomePage-Images/announcements.png) no-repeat left top;
}
</style>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
.ms-WPHeader TD[title^='Testing']
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
By using -----TD[title^='Testing']------  i m trying to find web part whose Title is Testing . It may be your is different.
After that i m giving background image for title. You can give any color.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
.ms-WPHeader TD[title^='Testing'] SPAN:first-child
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
This one i m using for putting style sheet for title(Testing" ). It may u need to set padding top for alignment.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ms-WPHeader TD[title^='Testing'] H3
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I m using this for left side image