Monday, 8 September 2014

SharePoint Repository Pattern Step By Step

This Post has been in my agenda for sometime but finally i got the time to write it:

I have done a lot of work with SharePoint API in my career path , and each time i see this code i become upset and feel angry even i  wrote this code many times :


             using (SPSite  site = new SPSite(path))
                {
                    using (SPWeb  web =  site.OpenWeb())
                    {
                          //Do work
                    }
              }


Problem:

Project  Solution (SPRepository)  will  consist of  three Projects:
  1. SPRepository.Core (class library): contains the Repository 
  2. SPRepository.Domin (class library) : Reference the (1) contains all entities 
  3. SPRepository.Portal (SharePoint Project). Reference  (1 and 2) and contains web parts(UI)




SPRepository.Core (class library): 


The class diagram for (SPRepository.Core) as below image (Figure1) 
Two weeks ago (today 3/10/2013) my manger asked me to make some changes on online Portal.
I got shocked on seeing hundreds of repeated codes.

I went to Google and start searching (sharepoint document repository).
But i didn’t find what i wants so i start reading and assembly parts to come up with complete solution that might help me and help others,
Of course i got some idea from other blogs.
Let's start talking about the Solution:


 Figure 1



Description of Class Diagram
class EntityBase
Is the base class of each entity  also please note that the entity represent SPList and contains the common Fields in SPList (ID , Title , Modified , Created, ModifiedBy , CreatedBy)


interface IMapper<TEntity>
Is the mapper that converts an entity of type (EntityBase) to and from SPListItem.
Its convert and SPListItem to EntityBase and vice versa


interface IRepository<TEntity>
contains all method that we need to work with SPList like Query , getting item and update item(SPListItem)


class Repository<TEntity> is the real implementation for IRepository<TEntity>

Let’s start by real example:

We have Department SPList with Fields
  1.    ID
  2.          Title
  3.           DeptCode

Also We have SPList called Employee with fields:
  1.                ID
  2.              Title
  3.               FirstName
  4.    LastName
  5.              Department (Lookup filed)





We will start by building Entity objects in the Project (SPRepository.Domin)
Add new class called Department inherited from Class EntityBase
and add Properties: (DeptCode , don't add other Properties because it's already in the base class EntityBase).



Add new class called Employee inherited from Class EntityBase
and add Properties:























 Okay don't upset it's very easy , we will start n example showing  step by step to how we can use the repository.




To be continue...

if you interested drop a comment











Friday, 5 September 2014

ajax error syntaxerror json parse unexpected token Jsonresult

I want Load Subcategories based on selected category using JQuery Ajax or JSON , on asp.net MVC application. 

Problem:
I've upgraded to VS.NET 2013, and now, every time I receive error when getting subcategories for category .

Error:jqXHR: 200textStatus: parser errorerror Thrown: SyntaxError: Unexpected token 


some solutions on internet was changing dataType:json or remove dataType and removing the content Type .. ,  i tried every possible solution with no luck.


after 4 hours of trying to solve the problem .i created on page with 2 dropdownlists only without master page, when i open HTML source code i found this line of code.


<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Chrome","requestId":"ac71e2a7594e4504a5135609483e8c7a"}
</script>
<script type="text/javascript" src="http://localhost:8157/eb9f5c3c339d488fb419a027dfa861bd/browserLink" async="async"></script>
<!-- End Browser Link -->



This is script is interfering with JQuery  library  and it crashes the jQuery reference.

this code came from new feature in visual studio 2013 called  Browser Link
After i disabled it the error went and every thing work as expected.





to disable it:




















Friday, 15 August 2014

A java Runtime Environment (JRE) or Java Development kit (JDK) must be available in order to run Eclipse

A java Runtime Environment (JRE) or Java Development kit (JDK) must be available in order

to run Eclipse. No Java virtual machine was found after searching the following locations:

 C:\eclipse\jre\javaw.exe javaw.exe in your current PATH



To solve this issue:

Download JAVA 64bit from this url http://www.java.com/en/download/manual.jsp



Wednesday, 21 May 2014

Stupid Things i used to do in SharePoint


Reading URL from from picture or hyperlink filed Using SPFieldUrlValue.

var newsLink = item.GetValueByInternalName("NewsLink").ToString();
newsLink = newsLink.Split(new char[] { ',' })[0];
objNewsInfo.NewsLink = newsLink;

you have to read it using  objNewsInfo.NewsLink = new SPFieldUrlValue(newsLink).Url;


Tuesday, 20 May 2014

Understanding elevated privileges in Sharepoint

Understanding elevated privileges:

 If your code runs in a farm solution within the SharePoint context, your code is executed by an IIS worker process (w3wp.exe).This process runs using the application pool identity associated with the SharePoint web application. ASP.NET applications, including SharePoint, use impersonation by default. This means that the application pool identity will impersonate the current user to execute code. As a result, your code can only perform actions that are permitted by the permission set of the current user.

When you use SPSecurity.RunWithElevatedPrivileges to invoke code, the worker process reverts to executing code using the application pool identity, rather than the identity of the current user. The application pool identity has full-trust permissions on the SharePoint web application. Consequently, your code is no longer restricted by the permission set of the current user.


Running code with elevated privileges is only applicable to code that runs within the SharePoint context. Code that runs without a SharePoint context—for example, code within a timer job—runs under a process identity rather than a user identity. In these scenarios, elevating privileges would have no effect, because the process is not impersonating the identity of a user. 


Note:

 You code run with elevated privileges only in farm solution,
 sandbox solution is executed withing isolated worker process.



many developer make a big mistake (me as well) and use SPSite object and SPWeb object from current context (SPContext) in elevated method , if you do so the elevated code will revert to running under the identity of current user.




Use SPSecurity.RunWithElevatedPrivileges to run code using the system account:


var dolegaDPO = New SPSecurity.CodeToRunElevated(DoPrivilegedOperation); 

SPSecurity.RunWithElevatedPrivileges(dolegaLODPO ); 
private void DoPrivilegedOperation()
{
  //type your code here
}

OR 



SPSocurity.RunWithElovatodPrivilogos( delegate() {

 //type your code here


});






Friday, 3 January 2014

Using OAuth Providers with MVC 4 to Get Extra Data like Email Gender Bithdate


I follow step by step this  article
http://www.asp.net/mvc/tutorials/security/using-oauth-providers-with-mvc

but unfortunately i was not able to get Facebook email  , birthday and gender.

after heavy search i found out you can solve this  problem by adjusting Facebook App
permission that user will be asked for by default.

okay i will tell you how.

by default when you create an App on Facebook they will not return email and gender they just will return
 basic info (name , link ...)


if you want get  extra data like gender and birthdate you have to change the permission for the application



     after i have changed permissions in Facebook  i got the data i want from Facebook


 



Wednesday, 25 December 2013

Paging With SPDataSource - best paging ever


Paging With SPDataSource (Very Easy)


I give up from SPListItemCollectionPosition and how it works and you have to pay too much attention to last item id and .... even i wrote an article about it you can see it here (paging with splistitemcollectionposition) but not now.


Now i am gonna show you an easy way for paging in very simple steps using SPDataSource


Add Visual Web Part (Contracts)  and on code behind add

 protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (gvContracts != null)
            {
                gvContracts.PagerTemplate = null;
            }
        }

Add SPGridView

  <SharePoint:SPGridView ID="gvContracts" DataSourceID="dsContracts" GridLines="None"
               AutoGenerateColumns="false" 
                 AllowPaging="true" PageSize="2" OnPageIndexChanging="gvContracts_PageIndexChanging"
                    runat="server" ShowHeader="false" OnRowDataBound="gvContracts_RowDataBound">                         <PagerStyle CssClass="gvfooter" />
                    <Columns>
                        <%# Eval("Title")%>
                    </Columns>
                 <PagerSettings Mode="NumericFirstLast" Position="Bottom" />
                </SharePoint:SPGridView>

Add SPDataSource

 <SharePoint:SPDataSource runat="server" ID="dsContracts" DataSourceMode="List">  <SelectParameters>
   <asp:Parameter Name="WebUrl" DefaultValue="/Arabic//TendersAndContracts" />
                        <asp:Parameter Name="ListName" DefaultValue="Contracts" />
                    </SelectParameters>
                </SharePoint:SPDataSource>


run your application and see 

Notes:
you can use it in more complex situations i already did it before.
wothout this line of code (  gvContracts.PagerTemplate = null;)
the pager  will not shown.


this sample image show paging for public portal using this paging with complex search






You are welcomed for any question, just drop me comment.