Wednesday, March 21, 2012

Search box disappears on search result page. - SharePoint 2010 Custom Master page 
[How to Stop That]

we are using our own master pages specially when it comes to the commercial system development (even sometimes we use V4 master page most of the tie we changed it or configure it according to the requirement). so we use search box with in our master page and it works fine. the problem here is when it comes to the search result page. The upper search box got disappear.

[In other pages search box is there]

[In Result page it disappear form the top]


I was wondering what happen there and it took about an hour to figure it out, what happen inside that.

What connection with PlaceHolderSearchArea
it's all stick with content place holder named or got id as "PlaceHolderSearchArea". search box placed inside that .

<!-- ------------| SEARCH BOX  |------------ -->
       <!-- search box loads from delegate, style with CSS -->
       <div class="s4-notdlg">
    <asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server"> 
<SPSWC:SearchBoxEx id="SearchBox" RegisterStyles="false" TextBeforeTextBox="" TextBoxWidth="50" GoImageUrl="<% $SPUrl:~sitecollection/Style Library/Images/search_icn.gif %>"
GoImageActiveUrl="<% $SPUrl:~sitecollection/Style Library/Images/search_icn.gif %>" GoImageUrlRTL="<% $SPUrl:~sitecollection/Style Library/Images/search_icn.gif %>"
GoImageActiveUrlRTL="<% $SPUrl:~sitecollection/Style Library/Images/search_icn.gif %>" UseSiteDefaults="false" DropDownMode="HideScopeDD" SuppressWebPartChrome="true"
runat="server" WebPart="true" __WebPartId="{0043945F-2D2B-4A02-8510-CED13B6F04DF}" SearchResultPageURL="<% $SPUrl:~sitecollection/pages/searchresult.aspx %>"  QueryPromptString="Search here..."/>

   </asp:ContentPlaceHolder>   
       
       </div>
       <!-- ------------| SEARCH BOX  |------------ -->



So You would need to remove the search box from the PlaceHolderSearchArea as that is the control that is replaced or disappears, when the search result page renders. but you need to make sure that you don't delete it (if you do that It'll get error when load result page)

so all you need to do is just create new place holder with different name Eg: PlaceHolderSearchArea1 and make previous one visible false using it's property and place your search box inside the newly created placeholder.


<!-- ------------| SEARCH BOX  |------------ -->
       <!-- search box loads from delegate, style with CSS -->
       <div class="s4-notdlg">
    <asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server" Visible="false"></asp:ContentPlaceHolder>

    <asp:ContentPlaceHolder id="PlaceHolderSearchArea1" runat="server">

<SPSWC:SearchBoxEx id="SearchBox" RegisterStyles="false" TextBeforeTextBox="" TextBoxWidth="50" GoImageUrl="<% $SPUrl:~sitecollection/Style Library/Images/search_icn.gif %>"
GoImageActiveUrl="<% $SPUrl:~sitecollection/Style Library/Images/search_icn.gif %>" GoImageUrlRTL="<% $SPUrl:~sitecollection/Style Library/Images/search_icn.gif %>"
GoImageActiveUrlRTL="<% $SPUrl:~sitecollection/Style Library/Images/search_icn.gif %>" UseSiteDefaults="false" DropDownMode="HideScopeDD" SuppressWebPartChrome="true"
runat="server" WebPart="true" __WebPartId="{0043945F-2D2B-4A02-8510-CED13B6F04DF}" SearchResultPageURL="<% $SPUrl:~sitecollection/pages/searchresult.aspx %>"  QueryPromptString="Search here..."/>

  </asp:ContentPlaceHolder>
       
       </div>
       <!-- ------------| SEARCH BOX  |------------ -->


then it will work fine.


ok That's It ... 
HAPPY CODING




Tuesday, March 13, 2012

Convert HTML to PDF using Sautin Soft Tool
[Generate PDF from HTML, ASPX, Images into your ASP.Net,WinForms and SharePoint applications]


There was a requirement in, one of my previous project is to convert SharePoint Page (aspx) in to a PDF and tat page create dynamically (it's not a static one). Clients' IT team have recommended to use Sautin Software tool for that.
Is It a Commercial Tool ?? If So Why we Used it ??
this is the first two question we got into our mind when we asked to do the task using this tool. "YES" It is a commercial tool. even we can use dll like iTextSharp  client recommend to use this because it's easy to handle and you don't need to write bunch of code to get the same result as u do with iTextSharp .
[FYI : use this link http://www.sautinsoft.com/products/convert-html-pdf-and-tiff-pdf-asp.net/html-to-pdf-jpeg-tiff-gif-to-pdf-asp.net.php to download or get more idea about sautin soft dll ] 


How To Use ?? 
It very easy to use all you need to do send the URL of the page which you need to convert to the dll and the path u need to save it as a pdf file (also you can create pdf bite stream and show it through the browser itself or give open/save option to the user )
In my project we have used pdf stream instead of saving file into default location. please refer the following code.


   // create pdf version object using SautingSoft namespace which responsible for  conversion         
            SautinSoft.PdfVision v = new SautinSoft.PdfVision();
  //when you purchase the dll you'll get the serial number please assign it  
            v.Serial = "0000000000"; (please don't use this number it's not a valid one)
  //declare byte stream  
            byte[] pdfBytes = null; 
 //Assign URL which need to convert
            string url =          string.IsNullOrEmpty(SPContext.Current.Site.WebApplication.GetResponseUri(Microsoft.SharePoint.Administration.SPUrlZone.Internet).OriginalString) ?
                SPContext.Current.Site.WebApplication.GetResponseUri(Microsoft.SharePoint.Administration.SPUrlZone.Intranet).OriginalString :
                SPContext.Current.Site.WebApplication.GetResponseUri(Microsoft.SharePoint.Administration.SPUrlZone.Internet).OriginalString;
           
//convert URL to pdf stream
            pdfBytes = v.ConvertHtmlFileToPDFStream(url + "/pages/partner_profile2.aspx?partnerid=" + Request.QueryString["partnerid"].ToString());


//show PDF
            if (pdfBytes != null)
            {
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = "application/PDF";
                Response.AddHeader("Content-Length", pdfBytes.Length.ToString());
                Response.AddHeader("Content-Disposition", "inline;filename=" +  DateTime.Now.Millisecond.ToString() + ".pdf");                
                Response.BinaryWrite(pdfBytes);
                Response.Flush();
                Response.End();
            }
Please consider on the highlighted area. we have a issue on this functionality. when we try to use this dll with authoring pages you cannot convert those authoring pages into PDF(you'll get a pdf file with error page "Page Cannot be Found"). 
But in our case we had Anonymous site also and this conversion work with that perfectly. we have chat with the Sautin Team, also but it cannot be done.

so in here what I have done is, Instead of giving the actual URL of the page I check whether it has Other URLs (like Anonymous ) then assign it. [SPContext.Current.Site.WebApplication.GetResponseUri(Microsoft.SharePoint.Administration.SPUrlZone.Internet).OriginalString ]. Give anonymous (internet URL) of the application.

Final Result ... 
Page which hold user detail.

when you click download PDF button. convert the page into PDF.
ok That's It ... 
HAPPY CODING





Monday, March 12, 2012

Search Service Configuration (Part 1)
[How to stop ?? admin content search through service]

I was reported some issue in one for my SharePoint project by client, it's regarding to the search functionality it said "the search function is displaying as a default search result. i.e. it is displaying admin section also." . what they mentioned is when they search something they get result which also related to the Admin section also like Central Administrator or other test sites.
this project we have used default search web parts and core result web parts to get and show the search results. means we cannot do many changes in web part levels. so what we need to do is, Looking at the search configuration.

Who Responsible .....
Service applications are responsible for many SharePoint services which provide through the framework. when you consider on search basically it's Search Service Application. so if you have a search service application then you get at-least something for search result when you search something . if you don't then you'll get something like following image, with error massage "The search request was unable to connect to the Search Service." when you search.


so if you don't have one just create one.
How To Create ... 
Login to central admin using the farm admin credential Access to  “Manage service applications” under  “Application Management” .

Then click on new and select Search Service application. 


Then Fill the required field in the popup. Give name as a Search Service Application (you can give any name you like, but this is much professional). 



you need to do some configurations, under the "Application Pool for Search Admin Web Service" and "Application Pool for Search Query and Site Settings Web Service". You can configure these section with new application pool or chose existing one (I recommend to chose existing one to eliminate configuration errors.). 

Then click OK, you get loading popup once it's creating.


Once it done you can search through the SharePoint Application but still that's not our main issue. Ore issue is how to stop getting Admin Content Search Results.

ISSUE .... 

The issue is on the search configuration (Central Admin level). The default configuration is (eg: All Site or Advanced Search) to get all the result related for the farm level that’s why you get all result including Admin level. 

SOLUTION ... 

To solve this issue we need to configure search service application and edit the Local SharePoint Site list.
for that we need to navigate to the Local SharePoint Site List . 
Go to The Manage service Applications (I explain the path above). then click Search Service Application.  


Click on  “Content Sources” under “Crawling” in the left navigation
Click on the dropdown arrow  “Local SharePoint sites” and click “Edit”





Under “Type start addresses below (one per line):” section you can see all the site URLs including admin level URLs also configured. 

Ensure the following values are set.
Remove all the URLs which already configured,
Give both <site> URL and the <anonymous site> URL as the “Start Address”
For the schedule of “Full crawl” and “Incremental crawl”, click on “Edit Schedule” and use the default and click OK [Scheduling part is optional you can schedule it or keep it as none for both Full Crawl and Incremental Crawl ]



At the end of this process start full crawl of this content source. Click on the dropdown arrow  “Local SharePoint sites” and click “Start Full Crawl”

Wait until the status part is “complete”. Then go to the application and Search something. It will only give the Site or Application Contents. 

ok That's It ... 
HAPPY CODING




Sunday, March 11, 2012

YouTube Video Play with SharePoint
[Bind YouTube thumbnails, Playing video with popup - Web part] 
There was a requirement to create web part (so called webTV ),in my first SharePoint project @ Navantis. Our client wants to show their videos which has been uploaded to the YouTube. web part should be nice looking with rotating options and it should bind with YouTube video thumbnail.
Rotating part can be done through some of JQueries you can get many examples from the internet on that. this is what we based on http://sorgalla.com/projects/jcarousel/examples/static_simple.html .

First Step ...
First step of creating Rotating panel was not that much hard. all you need to do is get all the required JS files and upload the in to the Style Library and link the with master page.

Second Step ...
we have to create a list which hold YouTube links and if required customized titles and descriptions . Then administrators can update related video links then the related videos can be watched through the web part.

Next Challenge (How to get Video thumbnail)...

In YouTube every video which has been uploaded. contain with several thumbnails (actually it contain with four thumbnails).
it has main thumbnail called zero jpg with a good resolution compare to others. and other images called 1 2 and 3 JPGs related to the video flash points.
YouTube thumbnail form with following address.
https://img.youtube.com/vi/"YouTube Video ID"/0.jpg ('0' can be as 1 2 or 3).

Flowing video view address is : http://www.youtube.com/watch?v=s12Jb5Z2xaE and it's video ID is 's12Jb5Z2xaE'


So by default it contain following images:
Zero Image : https://img.youtube.com/vi/s12Jb5Z2xaE/0.jpg

so as you can see zero image is the main one so all we need to do extract the video id from the link and form the image URLs and bind them with our control. 

How to Extract YouTube Video ID .... 

I have written a method for that with Reg-ex function. through following method you can extract the Video ID with any given Utube video link. 

private string GetYouTubeID(string youTubeUrl)
        {
            //RegEx to Find YouTube ID
            Match regexMatch = Regex.Match(youTubeUrl, "^[^v]+v=(.{11}).*",
                               RegexOptions.IgnoreCase);
            if (regexMatch.Success)
            {
                return regexMatch.Groups[1].Value;
            }
            return null;
        }


What's NEXT .... 
Then I wrote following function to bind all the required data into the repeater of the Web TV control . 

private DataTable GetWebListData()
        {
            DataTable retValue = null;

            if (SPContext.Current.Web != null)
            {
                SPWeb rootWeb = SPContext.Current.Web;
// Get the required list object and assigned it to the SPList [LIST_NEME is the nae of the link list which hold youtube links]
                SPList list = rootWeb.GetListFromUrl(string.Format("{0}{1}{2}{3}", rootWeb.Url, "/Lists/", LIST_NAME, "/AllItems.aspx"));
                SPQuery query = new SPQuery();

                // Order the items by the Index field of the list.
                query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE' /></OrderBy>";
                SPListItemCollection items = list.GetItems(query);

                retValue = new DataTable();
                retValue.Columns.Add("TargetURL");
                retValue.Columns.Add("PictureURL");
                retValue.Columns.Add("Description");

                foreach (SPListItem item in items)
                {
                    if (item[item.Fields.GetFieldByInternalName("URL").Id] != null)
                    {
                        string YouTubeVideoID = this.GetYouTubeID(item[item.Fields.GetFieldByInternalName("URL").Id].ToString());
                        if (!string.IsNullOrEmpty(YouTubeVideoID))
                        {
                            DataRow row = retValue.NewRow();
 // Here I create URL for embed YouTube video (which required for player), autoplay=1 means play as soon as get loaded with out waiting for user clicks play button.
                            row["TargetURL"] = "https://www.youtube.com/v/" + YouTubeVideoID + "&autoplay=1";
// Here I create URL for embed YouTube video (which required for player).
                            row["PictureURL"] = "https://img.youtube.com/vi/" + YouTubeVideoID + "/0.jpg";
                            row["Description"] = string.IsNullOrEmpty(item.DisplayName) ? "" : item.DisplayName;
                            retValue.Rows.Add(row);
                        }
                    }


                }


            }
            return retValue;
        }


please refer the following Tags which taken from related aspx file. The are which highlighted in yellow is responsible for rotating the control (I have user J Query for that.).
<script>

    $(document).ready(function () {
        //rotation speed and timer   
        var speed = 5000;
        var run = setInterval('rotate()', speed);

        var item_width = $('#WebTvslides li').outerWidth();
        var left_value = item_width * (-1);

        //move the last item before first item, just in case user click prev button
        $('#WebTvslides li:first').before($('#WebTvslides li:last'));

        //set the default item to the correct position
        $('#WebTvslides ul').css({ 'left': left_value });

        //if user clicked on prev button
        $('#WebTvprev').click(function () {

            //get the right position           
            var left_indent = parseInt($('#WebTvslides ul').css('left')) + item_width;

            //slide the item           
            $('#WebTvslides ul:not(:animated)').animate({ 'left': left_indent }, 200, function () {

                //move the last item and put it as first item             
                $('#WebTvslides li:first').before($('#WebTvslides li:last'));

                //set the default item to correct position
                $('#WebTvslides ul').css({ 'left': left_value });

            });

            //cancel the link behavior           
            return false;

        });
        //if user clicked on next button
        $('#WebTvnext').click(function () {

            //get the right position
            var left_indent = parseInt($('#WebTvslides ul').css('left')) - item_width;

            //slide the item
            $('#WebTvslides ul:not(:animated)').animate({ 'left': left_indent }, 200, function () {

                //move the first item and put it as last item
                $('#WebTvslides li:last').after($('#WebTvslides li:first'));

                //set the default item to correct position
                $('#WebTvslides ul').css({ 'left': left_value });

            });

            //cancel the link behavior
            return false;

        });


    });

    //a simple function to click next link
    //a timer will call this function, and the rotation will begin :)
    function rotate() {
        $('#WebTvnext').click();
    } 
        
</script>
<!--/Video Scripts-->
<script>
    $(document).ready(function () {
        //Examples of how to assign the ColorBox event to elements

        $(".youtube").colorbox({ iframe: true, innerWidth: 425, innerHeight: 344 });
        $(".callbacks").colorbox({
            onOpen: function () { alert('onOpen: colorbox is about to open'); },
            onLoad: function () { alert('onLoad: colorbox has started to load the targeted content'); },
            onComplete: function () { alert('onComplete: colorbox has displayed the loaded content'); },
            onCleanup: function () { alert('onCleanup: colorbox has begun the close process'); },
            onClosed: function () { alert('onClosed: colorbox has completely closed'); }
        });

        //Example of preserving a JavaScript event for inline calls.
        $("#click").click(function () {
            $('#click').css({ "background-color": "#f00", "color": "#fff", "cursor": "inherit" }).text("Open this window again and this message will still be here.");
            return false;
        });
    });
</script>
<!--/Video Scripts-->
<div class="wp_marginRight10">
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td align="center" valign="middle" class="vp_left">
                <a href="#" id="WebTvprev">
                    <img alt="" src='<asp:Literal runat="server" Text="<%$SPUrl:~sitecollection/Style Library/Images/NavantisIntranet/al.png %>" />' /></a>
            </td>
            <td class="vp_middle wp_videoImg">
                <div id="WebTvslides">
                    <ul>
                        <asp:Repeater ID="repeaterWebTV" runat="server">
                            <ItemTemplate>
                                <li><a class='youtube' href='<%# Eval("TargetURL").ToString() %>' title='<%# Eval("Description").ToString() %>'>
                                    <img src='<%# Eval("PictureURL").ToString() %>' alt="slide1" /></a> </li>
                            </ItemTemplate>
                        </asp:Repeater>
                    </ul>
                    <asp:Label ID="LabelError" runat="server"></asp:Label>
                    <div class="WebTvclear">
                    </div>
                </div>
            </td>
            <td align="center" valign="middle" class="vp_right">
                <a href="#" id="WebTvnext">
                    <img alt="" src='<asp:Literal runat="server" Text="<%$SPUrl:~sitecollection/Style Library/Images/NavantisIntranet/ar.png %>" />' />
                </a>
            </td>
        </tr>
    </table>
</div>


The Are which highlighted on Green is responsible for playing YouTube video with nice looking popup . Also you can see the repeater which hold the image and other required object. for the control . 

[for this you need to upload some JS and CSS files to style library and set their paths in side the master page.
JS:
jquery.jcarousel.min.js 
jquery.colorbox.js

CSS : 
SponsorsScroll.css
colorbox.css

(Download required files from : http://www.sendspace.com/file/1bdb5q )

Path Tags : 
<script type="text/javascript" src="/Style Library/Scripts/jquery.jcarousel.min.js"></script>
<script src="/Style Library/Scripts/jquery.colorbox.js"></script>
<link href="/Style Library/en-us/Core Styles/SponsorsScroll.css" rel="stylesheet"
    type="text/css" />
<link href="/Style Library/en-us/Core Styles/colorbox.css" rel="stylesheet" type="text/css" />


]

FINAL RESULT .... 






ok That's It ... 
HAPPY CODING