Thursday, 30 August 2012

How do check if file or image url exists using jQuery or Javascript json js ajax


Approach 1: (If its any file with any extension) :

To check whether files exist in file system, the best way to do this is with an AJAX HEAD request. HEAD requests only ask for and return the header from the destination file, so they’re much faster than POST or GET requests. Perfect for a simple file check.
It’s also returns the content length and last modified date and that jQuery has an “ifModified” option for the .ajax function that returns a Boolean value.
This jquery / javascript /js will be useful to check the image / file existence by providing source complete URL path  or relative URL path

Sample Demo Code

$.ajax({
    url:images/header.jpg',
    type:'HEAD',
    error:
        function(){
            alert(‘no File exist);
        },
    success:
        function(){
            alert(‘File exist’);        }
});

Approach 2 : (If its Image File with its related extension.)

The above approach is most recommended since this approach is not that much reliable and performance when compared to it to check existence.

HTML Source:
<img id=”image_id” src=” images/header.jpg” alt=”” />

JQuery:

This Jquery js will get call automatically when image is not available / loaded 
from file system or repository or directory.
 
$('#image_id').error(function() {

  alert('Image does not exist !!');

});
 

Wednesday, 22 August 2012

class library dll’s not added / installed / referenced / moved to assembly GAC while deployment of package automatically in SharePoint SP 2010 / 2007

To install classlibrary dll to GAC automatically during the deployment of WSP package of Sharepoint SP 2007 / 2010, refer the following instruction steps,

1. Open the Package designer in the SharePoint project.
2. Select the Advanced tab.
3. Click the Add button.
4. Select the Add Assembly from Project Output menu item.
5. Use the Source Project dropdown to select which project in your solution should have its assembly included.
6. Make sure the Deployment Target is set to GlobalAssemblyCache.
7. Click OK.
8. Repackage and redeploy the SharePoint project. 

The WSP package should now contain the class library's assembly and the WSP's package manifest should have been updated according.,

For more details, please refer : 

Tuesday, 14 August 2012

How to delete Corrupted / errored list / picture library in SharePoint SP 2010 /2007

The reason for  error like " Exception from HRESULT 0×81070215  " is custom list definition and list instance is not properly defined. That means field / columns in the content type has issues with that (some necessary fields / column might not be be defined there)
Please try to fix this by doing correct list definition, list instance and its content type otherwise delete the list using stsadm.exe force delete command

If you receive error Exception from HRESULT 0×81070215 when you open a list in browser or access the SharePoint site manager, a list has not properly been deleted and is in a corrupted state, which means you can not able to delete using browser hence you have to delete the corrupted list using stsadm forcedeletelist command.

Steps:

  • Go to start->run->cmd (it will open command window)
  • For Sharepoint 2007, Use cd C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN
  •  For Sharepoint 2010, Use cd C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN.
  • To find the help for forcedeletelist user following command,
    • Stsadm –help forcedeletelist
  • To delete particular corrupt list use following command,

Monday, 30 July 2012

Call or acess wcf webservice using ajax jquery code in asp.net c# javascript js

This code sample demonstrate how to pass with or without parameters to WCF service / web service method from client side code ajax jquery json js.
Unlike Javascript, Jquery provides rich access to service method in asp.net c#
 
With Parameters Sample

Client side code with dynamic and static text parameter to web service method from ajax json js With Parameters:-
 
function CallService()  
 { 
      var msg = ‘test message’;
     $.ajax( 
     { 
         Type: "POST", 
         contentType: "application/json; charset=utf-8",
         url: "ServiceName.asmx/WebMethodName", 
         data: "{ 'message': '"+msg+"' , ‘name’: 'test name' }",
         success: function (msg) { 
         alert(msg.d); 
         } 
     });

Server Side webservice / WCF method code :
 
[WebMethod()]
public static string WebMethodName(string message, string name)
{
return message + “--” + name;
}

Without Parameters Sample

Client side code without parameter to web service method from ajax json js With Parameters:-
 
function CallService()  
 { 
     $.ajax( 
     { 
         Type: "POST", 
         contentType: "application/json; charset=utf-8",
         url: "ServiceName.asmx/WebMethodName", 
         data: "{  }",
         success: function (msg) { 
         alert(msg.d); 
         } 
     });

Server Side webservice / WCF method code :

[WebMethod()]
public static string WebMethodName()
{
return “success”;
}

Thursday, 26 July 2012

Hiding / showing the SharePoint SP 2010 Ribbon From Anonymous restricted limited access Users in master edit page Privilege


How to hiding or showing ribbon control (with navigation breadcrumb) for anonymous or read access users like visitor or limited access users in sharepoint 2010 ( SP 2010 ) dynamically based on user's access:


SharePoint 2010 introduced new feature called “ Ribbon “ and it provides great user experience for users with elevated privileges, like contributors and site owners. However, Its not suggested for users with lease privilege, such as visitors and anonymous users since most of features are applicable for them.
SPSecurityTrimmedControl which  is used to show / hide the ribbon control.

Steps:

1)      Open your SharePoint master page to edit it.

2)      Find the following line wth the highlighted text in your master page.

       <div id="s4-ribbonrow" class="s4-pr s4-ribbonrowhidetitle">
     Note: This div only contains the whole part of out of box sharepoint ribbon control.

3)  To hide the above div element, Find the following line in your master page.

      <div id="s4-workspace"

4)  Now add the following code in your master page just above the “s4-workspace” div element.

   <Sharepoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl2" runat="server" PermissionsString="ManagePermission">
    <script type="text/javascript">
        document.getElementById("s4-ribbonrow").style.display = "none";
    </script>
</
Sharepoint:SPSecurityTrimmedControl>

5)      To apply changes, Save the master page and publish it.




Assigning permission programmatically for document libray or list item sharepoint 2010 code sp 2010


How to access or Assigning permission dynamically to Document library / List library / List Item / picture library on folder in sharepoint 2007 / 2010 ( SP 2010 ) code :

Windows SharePoint 2010 / 2007 provides Services manages permissions through Roles and Responsibilities. SPRoleDefinition and SPRoleDefinition classes provides methods to assign users to roles such as “Contributor” or “Site Owner” or “Reader.

Sample solution code:

Following code demonstrate how to assigning / access “Reader” to custom SharePoint group “customgroup” programmatically on Folder of a document library for a custom sharepoint group by code method

using (SPSite site = new SPSite(siteCollection))
{
  using (SPWeb web = site.OpenWeb(siteName))
  {
    SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists[libraryName];
    //Get folder
    SPListItem item = docLib.Folders[1];
    if (!item.HasUniqueRoleAssignments)
      item.BreakRoleInheritance(true);
    SPRoleAssignment roleAssignment = new SPRoleAssignment(“customgroup”);
    SPRoleDefinition roleDefination = web.RoleDefinitions["Reader "];

    roleAssignment.RoleDefinitionBindings.Add(roleDefination);
    item.RoleAssignments.Add(roleAssignment);
    item.Update();
  }
}

Assigning permission programmatically for site collectin and its sub site item sharepoint 2010 code sp 2010

How to Assigning permission programmatically / dynamically to site collection or its sub site in sharepoint 2007 / 2010 ( SP 2010 ) code

Windows SharePoint 2010 / 2007 (SP 2010) Service manages permissions through Roles and Responsibilities. SPRoleDefinition and SPRoleDefinition classes provides methods to assign users to roles such as “Contributor” or “Site Owner” or “Reader

Sample solution code:

Following code demonstrate how to assign / access  “Reader” to custom SharePoint group “customgroup” programmatically / dynamically by code class method and access the site collection and its sub sites as “reader” permission in sp2010.


using (SPSite site = new SPSite(siteCollection))
{
  using (SPWeb subWeb = site.OpenWeb(siteName))
  {
    //You need to break role inheritence if you want to assign unique permission to subsite
    if (!subWeb.HasUniqueRoleAssignments)
      subWeb.BreakRoleInheritance(true);
    SPRoleDefinition roleDefination = parentWeb.RoleDefinitions["Reader"];
    SPRoleAssignment roleAssignment = new SPRoleAssignment("customgroup");
    roleAssignment.RoleDefinitionBindings.Add(roleDefination);
    subWeb.RoleAssignments.Add(roleAssignment);
    subWeb.Update();
  }
}

Wednesday, 25 July 2012

Delete Close Web Parts SharePoint 2010 url


How to delete or close Web Parts on SharePoint 2010 or What is The URL for deleting or closing webparts in sharepoint 2007 / 2010 pages :

Using webpart Maintenance Page mode:


We just need to  go to the Web Part Maintenance Page of SharePoint 2010. and then append just , ?contents=1

This URL of Maintenance Page of SharePoint 2010, will display all webparts which were used in page.
This URL will show all current using webparts and closed webparts ( not deleted webparts).

Sample solution URL for delete or close the webpart would be like,

http://yourdomain.com/pages/home.aspx?contents=1


Using Normal Manual Mode :
 
To delete a Web part, do the following:
1. Open the page where the Web part is located.
2. Select Edit Page from the Site Actions drop-down menu.
3. Click the Web part to be deleted.
4. Click the Web Part Tools tab on the Ribbon.
5. Click the Delete Button, and then click OK in the warning dialog.
 

Monday, 23 July 2012

this implementation is not part of the windows platform fips validated cryptographic algorithms

Problems / Issues with  “ this implementation is not part of the windows platform fips validated cryptographic algorithms ” with visual studio 2010 with windows 7 operating system :-

Solution for this problem is,

enforceFIPSPolicy is a .Net 2.0 SP1 config file switch which helps the application to opt out FIPS checking.

How to  fix / avoid this issue / problem “ this implementation is not part of the windows platform fips validated cryptographic algorithms ” in VS 2010 :-

To avoid the issue with Visual Studio 2010, we could follow the steps,
  • Open Devenv.exe.config from
    C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE “  if your OS is x64 bit
    otherwise “ C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\on x86 OS
  • Do find </runtime> tag and add the following code tags,
    <enforceFIPSPolicy enabled="false"/>
  • After adding the  code into “ devenv.exe. config “ file and it would looks like,
<configuration>
<runtime>
.
.
.
<
enforceFIPSPolicy enabled="false"/>
</runtime>
</configuration>
  • Do restart Visual Studio 2010 / VS 2010

Monday, 7 May 2012

Listbox move updown rightleft jquery


Listbox Move Up Down Right Left Delete Item value show / select all check list items in asp.net controls using jquery js sample demo code:


This jquery/js will perform the following function (not by using javascript method)...

1. Move list items between two listbox with multiple move option
2. Delete List Item / multiple list items.
3. Move list items up and down (multiple)
4. Seletet / read all list items. (option to show selected list items is commented in jquery js code)



Script sample demo code
<script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function() {
            $("#MoveRight,#MoveLeft").click(function(event) {
                var id = $(event.target).attr("id");
                var selectFrom = id == "MoveRight" ? "#from" : "#to";
                var moveTo = id == "MoveRight" ? "#to" : "#from";

                var selectedItems = $(selectFrom + " :selected").toArray();
                $(moveTo).append(selectedItems);
                selectedItems.remove;
            });
        });
    //function moveUp() {
    $(function() {
    $("#MoveUp").click(function(event) {
  
    $('#to :selected').each(function(i, selected) {
        if (!$(this).prev().length) return false;
        $(this).insertBefore($(this).prev());
    });
    $('#to select').focus().blur();
  
});
});

//function moveDown() {
$(function() {
$("#MoveDown").click(function(event) {
    $($('#to :selected').get().reverse()).each(function(i, selected) {
        if (!$(this).next().length) return false;
        $(this).insertAfter($(this).next());
    });
    $('#to select').focus().blur();
  
});
});
$(function() {
$("#ReadAll").click(function(event) {
$('#to option').each(function(index) {
//  if ( ($(this).is(':selected')) {
//    // do stuff if selected
//  }
//  else {
//   // this one isn't selected, do other stuff
//  }
alert($(this).val()+'--' + $(this).text());
});
});
});
$(function() {

$("#Delete").click(function(event) {
    $('#to :selected').each(function(i, selected) {
      
        $(this).remove();
        alert('Selected item deleted');
       $('#to').focus().blur();
  
});
});
});

    </script>
 
 
 
HTML APSX Source code 

<div>
    <asp:ListBox ID="from" runat="server" SelectionMode="Multiple">
    <asp:ListItem Value="f1">frm list 1</asp:ListItem>
    <asp:ListItem Value="f2">frm list 2</asp:ListItem>
    <asp:ListItem Value="f3">frm list 3</asp:ListItem>
    <asp:ListItem Value="f4">frm list 4</asp:ListItem>
    <asp:ListItem Value="f5">frm list 5</asp:ListItem>
    </asp:ListBox>
 
   
    <input id="MoveRight" type="button" value=" >> " />
    <input id="MoveLeft" type="button" value=" << " />
    <input id="MoveUp" type="button" value=" UP " />
    <input id="MoveDown" type="button" value=" Down " />
    <input id="Delete" type="button" value=" Delete Item " />
    <input id="ReadAll" type="button" value=" Read All " />
     
    <asp:ListBox ID="to" runat="server" SelectionMode="Multiple">
    <asp:ListItem Value="to1">to list 1</asp:ListItem>
    <asp:ListItem Value="to2">to list 2</asp:ListItem>
    <asp:ListItem Value="to3">to list 3</asp:ListItem>
    <asp:ListItem Value="to4">to list 4</asp:ListItem>
    <asp:ListItem Value="to5">to list 5</asp:ListItem>
    </asp:ListBox>
    </div>

Thursday, 19 April 2012

textbox watermark javascript jquery

How to add watermark to single/multiple textbox control using javascript/jquery js in Asp.net C# code:

The below sample has two approach by using jquery as well as javascript js.


Sample ASPX source code sample:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>

    <script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">

/* js on load method*/  

$(document).ready(function() {
     var watermark = 'Enter your text';
     $('#txtBox').blur(function(){
      if ($(this).val().length == 0)
        $(this).val(watermark).addClass('watermark');
     }).focus(function(){
      if ($(this).val() == watermark)
        $(this).val('').removeClass('watermark');
     }).val(watermark).addClass('watermark');
    });

/* javascript function*/   
    function watermark(inputId,text){
      var inputBox = document.getElementById(inputId);
        if (inputBox.value.length > 0){
          if (inputBox.value == text)
            inputBox.value = '';
        }
        else
          inputBox.value = text;
    }
    </script>
  
    <style type="text/css">
    #txtBox.watermark { color: #999; } /*Gray color*/
    </style>
  
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtBox" runat="server"></asp:TextBox>
  
    <asp:TextBox ID="txtName" runat="server" Text="Enter your name" onfocus="watermark(this.id,'Enter your name');" onblur="watermark(this.id,'Enter your name');"></asp:TextBox>
    <asp:TextBox ID="txtAddress" runat="server" Text="Enter your Address" onfocus="watermark(this.id,'Enter your Address');" onblur="watermark(this.id,'Enter your Address');"></asp:TextBox>
    </div>
    </form>
</body>
</html>

calling server side function/method jquery-ajax


How to Call server side C# asp.net code behind method/ function from client side code using ajax jquery/json js:

The below sample demonstrate how to call server side web method/function using jquery js not by javascript.

This sample code also shows how to call web method from asp.net button control (server side control) and HTML hyperlink anchor tag (client side control)

Sample ASPX source code:
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
   
    <script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
   
     <script type ="text/javascript">
         $(document).ready(function () {
            $('#<%=Button1.ClientID %>').click(function () {
                $.ajax({
                    type: "POST",
                    url: "serversidecallfromjs.aspx/callServerMethod",
                    data: "{}", /*indicates no parametre is passed to web method/function*/
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,
                    cache: false,
                    success: function (msg) {
                      $('#msgDiv').text(msg.d);
                   }
                })
               return false;
             });
       });

function callm()
{

 $.ajax({
                    type: "POST",
                    url: "serversidecallfromjs.aspx/callServerMethod1",
                    data: "{'parname': 100}" /*if any parametre is there means {'parname': 1}*/,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,
                    cache: false,
                    success: function (msg) {
                      $('#msgDiv').text(msg.d);
                   }
                })
                return false;
}

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="Button1" runat="server" Text="Click" />
    <br />
    <a href="#" onclick="callm();">Click 2 clock</a>
    <br />
    <div id="msgDiv"></div>
    </div>
    </form>
</body>
</html>

Code behind:
 
using System.Web.Services;

namespace MyWebApps
{
    public partial class serversidecallfromjs : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static string callServerMethod()
        {
            return "Response from server.";
        }
        [WebMethod]
        public static string callServerMethod1(string parname)
        {
            return "Response from server" + parname + ".";
        }
      
    }
}
 

Wednesday, 18 April 2012

Create/Read global resource file code asp.net

How to Create/Read global resource file using asp.net code behind c#:

How to create Global resource file:

Steps:
1.Right click on web project and select Add --> Add ASP.Net Folder option
2.App_GlobalResources folder will be added.
3.Right click on "App_GlobalResources" folder and select Add --> Resource File --> give name  --> ok

example: 

readglobalresoircefile.resx  // global/default language
readglobalresoircefile.en-US.resx  // english language
readglobalresoircefile.fr-FR.resx  // french language
readglobalresoircefile.es-ES.resx  // spanish language

4.Add new key value. for example:
Key        value
------     ------
aa         English aa test
bb         English bb test


How to read/get Global resource file key value from code behind asp.net C#

Add the following Namespaces.

using System.Resources;
using System.Globalization;

Add the following code inside your custom function/method or in page load.

Source code sample:

ResourceManager rm = new System.Resources.ResourceManager("Resources.readglobalresoircefile", System.Reflection.Assembly.Load("App_GlobalResources"));
string ress = "en-US";  // to read us english resource.. if it is french then the culture code will be fr-FR likewise.
CultureInfo ci = new System.Globalization.CultureInfo(ress);
string resstring = rm.GetString("aa", ci);  // where aa indicates global resource file key value

we could assign this "resstring" string variable to any of asp.net control like textbox, label..

Monday, 9 April 2012

jquery for each loop to read elements

How to read elements by using for each loop in jquery ?

function(index, Element) -- A function to execute for each matched element.

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

Example  1: Iterates through the array displaying each value text:

<script type="text/javascript">

var arrvar = [ "sample javascript code1", "sample javascript code2", "sample javascript code1", "sample javascript code1", "sample javascript code1" ];


    jQuery.each(arrvar, function() {
         alert(this);
      });

</script>

Example 2:Iterates over div elements /controls

      <div id="div1">jquery call 1</div>
      <div id="div2">javascript alert 1</div>
      <div id="div3">jquery call 2</div>
      <div id="div4">javascript alert 2</div>
      <div id="div5">jquery call 3</div>

<script type="text/javascript"> 

//$(document).click(function() { // onclick of body content call $(document).ready(function() {
 
      $("div").each(function () {
        alert($(this).text());
      });
    });

</script>

 

 

 

Sunday, 8 April 2012

Steps to create and reorder a tab in FAST search center SP 2010

How to create and reorder a tab in FAST search center Sharepoint 2010

Steps:

1.Open the SharePoint site.
2.Go to ->Site Actions->View all Contents
3.We have two lists namely – “Tabs in Search Pages” and “Tabs in Search Results” which controls the tab in Search page and Search results page respectivly.



4.Open the list “Tabs in Search Pages”.
5.Click on Item in the ribbon control present at the top of the page and select “New Item”.
6.A form appears. Provide the proper tab name. (eg:“Old Site”).
7.In the Page filed we need to enter the page name, this can be out-of-the box page name or create a new page and include it.
Follow the above steps for the other list also.





Steps to reorder the tabs displayed in the Search center

There is No UI for changing the order of the Tab that appears in Search Center. There is two work around available for this, But the below one would be the easiest one.
1.Open the SharePoint site.
2.Go to “Site Actions”->”View All Site Contents”
3.Select the list ”Tab in search page”
4.Click on “List” in the ribbon control present at the top of the page.
5.Select ”List Settings” present at the right hand corner of the tab that appears when clicked on “List”
6.In the URL change the “listedit.aspx” to “reorder.aspx”








7.Change the order and save it.
8.Still we have to make one more thing before we see the correct order in search center.
9.Go back to the list “Tabs in Search Pages” and edit any of the items (no changes required) just save it again to let SharePoint know that some modification is happen in the TAB.