Sunday, 31 July 2016

Exception calling "ChangeDatabaseInstance" with "1" argument(s)

PS C:\Users\admin> $db.ChangeDatabaseInstance("DBNAME")
Exception calling "ChangeDatabaseInstance" with "1" argument(s): "An update
conflict has occurred, and you must re-try this action. The object SPServer
Name=SERVERNAME was updated by admin, in the powershell (2572)
process, on machine SERVERNAME.  View the tracing log for more information
about the conflict."
At line:1 char:1



Solution: Clear the Cache

Run the below script

Add-PSSnapin -Name Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

Stop-Service SPTimerV4
$folders = Get-ChildItem C:\ProgramData\Microsoft\SharePoint\Config
foreach ($folder in $folders)
    {
    $items = Get-ChildItem $folder.FullName -Recurse
    foreach ($item in $items)
        {
            if ($item.Name.ToLower() -eq "cache.ini")
                {
                    $cachefolder = $folder.FullName
                }
               
        }
    }
$cachefolderitems = Get-ChildItem $cachefolder -Recurse
    foreach ($cachefolderitem in $cachefolderitems)
        {
            if ($cachefolderitem -like "*.xml")
                {
                   $cachefolderitem.Delete()
                }
       
        }
       
$a = Get-Content  $cachefolder\cache.ini
$a  = 1
Set-Content $a -Path $cachefolder\cache.ini


Sunday, 24 July 2016

Could not load file or assembly '$SharePoint.Project.AssemblyFullName$' or one of its dependencies

Error=Could not load file or assembly '$SharePoint.Project.AssemblyFullName$' or one of its dependencies. The system cannot find the file specified.



Solution:--


The fix is simple, do the following:

1.  Open your project file .csproj  Edit the .csproj file in NotePad
2.  Find the PropertyGroup nodes.
3.  Add a new PropertyGroup node.
<PropertyGroup>
<TokenReplacementFileExtensions>ashx</TokenReplacementFileExtensions>
</PropertyGroup>
4.  Re-Open your project file

HTTPHandler in Sharepoint

1.Create empty project
2.Add HTTPHandler class from Teamplate if not exist then create manually
3.Open .asxh file paste the below code as per you project Name and Class name

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ WebHandler Language="C#" CodeBehind="FileUploader.ashx.cs" Class="SharePointProject1Test.Layouts.SharePointProject1Test.FileUploader" %>

and .ashx.cs code like below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Microsoft.SharePoint;
namespace SharePointProject1Test.Layouts.SharePointProject1Test
{
    /// <summary>
    /// Summary description for FileUploader
    /// </summary>
    ///
 
    public class FileUploader : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
         
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection files = context.Request.Files;
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[i];
                    AddFile(file.InputStream,file.FileName);
                 
                }
                context.Response.ContentType = "text/plain";
                context.Response.Write("File Uploaded Successfully!");
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }



        public static void AddFile(Stream inputStream,string fileName)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate() {

            using (SPSite site = new SPSite("http://siteName"))
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    byte[] bytes = StreamToByteArray(inputStream);
                    SPFolder myLibrary = web.Folders["Documents_test"];
                    SPFile spfile = myLibrary.Files.Add(fileName, bytes, true);
                    myLibrary.Update();
                    web.AllowUnsafeUpdates = false;
                }
                site.AllowUnsafeUpdates = false;

            }
            });
        }
        public static byte[] StreamToByteArray(Stream inputStream)
        {
            byte[] bytes = new byte[16384];
            using (MemoryStream memoryStream = new MemoryStream())
            {
                int count;
                while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
                {
                    memoryStream.Write(bytes, 0, count);
                }
                return memoryStream.ToArray();
            }
        }
    }
}



4.In the Solution Explorer, click the .ashx file and in the Properties pane, set the Build Action to Content.
5. In the Solution Explorer, click the .ashx.cs file and in the Properties pane, set the Build Action to Compile.
6. Now we need to Save and Close the solution.
7. Edit the .csproj file and add the following text to a PropertyGroup,

<PropertyGroup>
<TokenReplacementFileExtensions>ashx</TokenReplacementFileExtensions>
</PropertyGroup>

8. and reload your project in Visual Studio.
9. test the HTTPHandler open browser and paste url like below
 http://SiteName/_Layouts/15/SharePointProject1Test/FileUploader.ashx
9. now HTTPHandler will catch the event and give a message
10. To call HTTPHandler in JQuery/JavaScript paste the code in your Visua webpart / applicationpage / in Content Editor Webpart like below

<script src="/_layouts/15/SharePointProject1Test/jquery-1.4.1.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#btnUpload").click(function () {

            uploadfile();


        });
    });

    function uploadfile() {
        var bannerImage = $("#fupload").val();

        if (bannerImage) {
            var file = document.getElementById('fupload').files[0];
            var formData = new FormData();
            formData.append(file.name, file);
            var xhr = new XMLHttpRequest();
            var url = "/_Layouts/15/SharePointProject1Test/FileUploader.ashx";
            xhr.open('POST', url, true);
            xhr.onload = function (e) {
                var response = $.parseJSON(e.target.response);
alert(response);
           
            };

            xhr.send(formData);  // multipart/form-data

        }
    }
</script>

 <h3>Upload file Using HTTPHandler in SharePoint</h3>
    <table>
        <tr>  
        <td>
            <input id="fupload" type="file"/><br />
            </td>
 
        </tr>
        <tr>
 
        <td><input id="btnUpload"  value="Upload Selected File" type="button" /></td>
        </tr>
    </table>


Start A workflow programtically in sharepoint

private void StartWorkflowInstance()
        {
           
       
            try
            {

                //SPWorkflowManager objWorkflowManager = listItem.Web.Site.WorkflowManager;
                SPWorkflowManager objWorkflowManager = SPContext.Current.Web.Site.WorkflowManager;
                SPList _list = SPContext.Current.Web.Lists["listname"];
                SPListItem _listItem = _list.GetItemById(listItem.ID);

                if (objWorkflowManager.GetItemWorkflows(_listItem).Count == 0)
                {
                    SPWorkflowAssociationCollection objWorkflowAssociationCollection = _listItem.ParentList.WorkflowAssociations;

                    foreach (SPWorkflowAssociation objWorkflowAssociation in objWorkflowAssociationCollection)
                    {
                        if (objWorkflowAssociation.Name == rbClassificationOfOutgoingDocument.SelectedItem.Text  + " "+ ProcessModelOneConstants.FullAdHocWrokflowName)
                        {
                            SPWorkflow activeWorkflow = objWorkflowManager.StartWorkflow(_listItem, objWorkflowAssociation, objWorkflowAssociation.AssociationData, true);
                            SPUser initiator = activeWorkflow.AuthorUser;
                            string initName = initiator.Name;
                        }
                    }
                }
            }
            catch (Exception exception)
            {

            }
        }

Friday, 22 July 2016

Wait message in Sharepoint

For Client Side  code


//////////////////Wait and Close Dialog box//////////

    function WaitMessage() {
        window.parent.eval("window.waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Wait request is processing..', '', 90, 50);");
    }

// close message
    function CloseWaitDialog() {
        if (window.frameElement != null) {
            if (window.parent.waitDialog != null) {
                window.parent.waitDialog.close();
            }
        }
        else
        {
            if (window.parent.waitDialog != null)
            {
                window.parent.waitDialog.close();
            }
        }

    }
//////////////////////////////


Use like below

<script>
$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', readyFunction);
});

function readyFunction() {
    WaitMessage();
 
////////////////////Write your long code here
 
    CloseWaitDialog();
}
</script>



if you want to call it server side please put the code like below


<asp:Button runat="server" ID="Button" Text="Submit" OnClick="Button_Click" OnClientClick="javascript:WaitMessage();" />

protected void Button_Click(object sender, EventArgs e)
         {
              // Do the complex operations here and at the end of the complex operation, we need to close the dialog box which we opened.

             this.ClientScript.RegisterStartupScript(this.GetType(), "CloseWaitDialog", @"
                     <script language='javascript'>
                         if (window.frameElement != null) {
                             if (window.parent.waitDialog != null) {
                                 window.parent.waitDialog.close();
                             }
                         }
                     </script>");
         }





Wednesday, 13 July 2016

Querystring value in JQuery/Javascript

function getQueryStringParameter(paramToRetrieve) {
        var params =
            document.URL.split("?")[1].split("&");
        var strParams = "";
        for (var i = 0; i < params.length; i = i + 1) {
            var singleParam = params[i].split("=");
            if (singleParam[0] == paramToRetrieve)
                return singleParam[1];
        }
    }

formated date in jquery/javascript

function getFormattedDate(formatedDate) {
  var year = formatedDate.getFullYear();
  var month = (1 + formatedDate.getMonth()).toString();
  month = month.length > 1 ? month : '0' + month;
  var day = formatedDate.getDate().toString();
  day = day.length > 1 ? day : '0' + day;
  return month + '/' + day + '/' + year;
}