Skip to main content

Blog de Alejandro Avila

Go Search
Home
  

 Documents

Paper Browser.8.5x11.Horizontal.pdfPaper Browser.8.5x11.HorizontalAlex Ávila
sketching.pdfsketchingAlex Ávila
website-stencil-template-a4.pdfwebsite-stencil-template-a4Alex Ávila
concept7_a4_sketching_paper_v01.pdfconcept7_a4_sketching_paper_v01Alex Ávila
mbti_sketching_concept7_a4.pdfmbti_sketching_concept7_a4Alex Ávila
PeopleSearchResultsCustomization.pptPeopleSearchResultsCustomizationAlex Ávila
Taxonomy-Sharepoint-2009.pptTaxonomy-Sharepoint-2009Alex Ávila
Upload file creating folder SP2010
var clientContext = new ClientContext("http://server2010/sub");

var FileSrvRelUrl = "/sub/SuperDocLibWithFields/Folder1/File3.txt";
using (var fileStream = new MemoryStream(new byte[100]))
{
    Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, FileSrvRelUrl, fileStream, false);
}
var web = clientContext.Web;
var f = web.GetFileByServerRelativeUrl(FileSrvRelUrl);
var item = f.ListItemAllFields;
item["NewCol"] = "Value";
item["Author"] = 66;
item["Editor"] = 67;

item["Created"] = DateTime.Now.AddYears(-10);
item["Modified"] = DateTime.Now.AddYears(-5);
item.Update();
clientContext.Load(item, i=>i.Id);
clientContext.ExecuteQuery();

Console.WriteLine("Item id {0}",item.Id);
 
Enable anonymous access sp2010
 

Ok, its not really a branding tip, but I’m on a roll here. In SharePoint 2010 if you want to setup your site to allow anonymous visitors, the process is much like it is in SharePoint 2007 except that the ribbon is now part of of the process. While I have really gotten used to the ribbon, this option I find particularly confusing. Just like in SharePoint 2007 the process begins in Central Administration, either you set the web application to Allow Anonymous access in the initial web application creation screen OR you need to set it afterward. If you are going to set it after, click on Manage Web Applications and select a web application from the list and take a look at the ribbon:

image

You might be inclined to click Anonymous Policy as I was initially but this does NOT allow you to turn on Anonymous access. Instead click Authentication Providers:

image

From this menu you select an Authentication Provider:

image

The from the next menu you can check Enable anonymous access:

image

After you click save, the web application will allow Anonymous access to be set, but you have to set this from the actual web application. So now, navigate to the top level site collection for the web application and click Site Actions > Site Settings > Site Permissions. From that menu you can click Anonymous Access:

image

From there select Entire Web Site and click OK:

image

That’s all you have to do, now the site will be available for browsing by anyone. Really only the first step is confusing compared to SharePoint 2007.

 
Upload Document with Item Fields in a Document Library with OM SP2010
 
I was searching how to upload a document into a document library adding some fields. But I haven't find anything with the client object model.
 
Then I have to make my own functions where first of all I upload the file and then I search for the file and update his fields.
 
This is my code:
 
static void Main(string[] args)

{

string attachedFile = @"C:\\test\\test.docx";

string spFilepath = UploadFile(attachedFile);

SetFileFields(spFilepath);

Console.Write("Press any key to exit...");

Console.ReadLine();

}

public static string UploadFile(string attachFilePath)

{

ClientContext clientContext = new ClientContext("http://mysite/");

clientContext.Credentials = new NetworkCredential("user", "pass");

List l = clientContext.Web.Lists.GetByTitle("listTitle");

Folder f = l.RootFolder;

clientContext.Load(f);

clientContext.ExecuteQuery();

string spFilepath = string.Empty;

using (FileStream strm = new FileInfo(attachFilePath).Open(FileMode.Open))

{

spFilepath = Combine(f.ServerRelativeUrl, Path.GetFileName(attachFilePath));

Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, spFilepath, strm, true);

}

clientContext.ExecuteQuery();

return spFilepath;

}

public static void SetFileFields(string spFilepath)

{

ClientContext clientContext = new ClientContext("http://mysite/");

clientContext.Credentials = new NetworkCredential("user", "pass");

List l = clientContext.Web.Lists.GetByTitle("listTitle");

FileCollection fc = l.RootFolder.Files;

clientContext.Load(fc, files => files

.Include(

file => file.Name,

file => file.ServerRelativeUrl)

.Where(file => file.ServerRelativeUrl == spFilepath )

);

clientContext.ExecuteQuery();

if (fc.Count > 0)

{

Microsoft.SharePoint.Client.File file = fc[0];

ListItem listItem = file.ListItemAllFields;

listItem["field1"] = 2;

listItem["field2"] = "value2";

listItem["field3"] = DateTime.Now;

listItem["field4"] = "value3";

listItem.Update();

}

clientContext.ExecuteQuery();

}

static string Combine(string baseUrl, string relativeUrl)

{

string cleanBaseUrl = baseUrl.Replace("\\", "/");

string cleanRelativeUrl = relativeUrl.Replace("\\", "/");

cleanBaseUrl = cleanBaseUrl.TrimEnd(new char[] { '/' });

cleanRelativeUrl = cleanRelativeUrl.TrimStart(new char[] { '/' });

return string.Format("{0}/{1}", cleanBaseUrl, cleanRelativeUrl);

}

 
Please if someone knows a better way or the microsoft way I'll be glad to read your code in the comments
 
Missing System.Web at Console Application with VS2010
 
But then I checked the Project Properties and noticed the Target Framework was indeed set to ".NET Framework 4 Client Profile". When I set it to ".NET Framework 4" the "Add Reference" dialog showed the System.Web assembly again. Thanks for the solution.
 
Entity Framework ObjectContext as Singleton
 
public class SharedObjectContext
{
    private readonly WestwindEntities context;

    #region Singleton Pattern

    // Static members are lazily initialized.
    // .NET guarantees thread safety for static initialization.
    private static readonly SharedObjectContext instance = new SharedObjectContext();

    // Make the constructor private to hide it.
    // This class adheres to the singleton pattern.
    private SharedObjectContext()
    {
        // Create the ObjectContext.
        context = new WestwindEntities();
    }

    // Return the single instance of the ClientSessionManager type.
    public static SharedObjectContext Instance
    {
        get
        {
            return instance;
        }
    }  

    #endregion

    public WestwindEntities Context
    {
        get
        {
            return context;
        }
    }
}
 
 
for ASP.NET
 
public static class ObjectContextPerHttpRequest
{
    public static WestwindEntities Context
    {
        get
        {
            string objectContextKey = HttpContext.Current.GetHashCode().ToString("x");
            if (!HttpContext.Current.Items.Contains(objectContextKey))
            {
                HttpContext.Current.Items.Add(objectContextKey, new WestwindEntities());
            }
            return HttpContext.Current.Items[objectContextKey] as WestwindEntities;
        }
    }
}
 
An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager.
I've starte to work with Entity Framework 4.0 recently and I developed a repository class IDisposable which contains the db context. I have to made it IDisposable because the ObjectContext is IDisposable and I had to dispose the context when I finish the transactions.
 
I had an exception while I am saving, and I finally found this issue (it's a simplification):

tbl_Alias_Node t;

using (OMCMSNET_Entities db = new OMCMSNET_Entities())

{

t = db.tbl_Alias_Node.Single(tbl => tbl.id == 1);

t.alias = "myAlias";

}

using (OMCMSNET_Entities db = new OMCMSNET_Entities())

{

db.tbl_Alias_Node.ApplyCurrentValues(t); (exception)

db.SaveChanges();

}

 
I don't know why but, this code generates this exception:
 
"An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. Verify that the key values of the supplied object match the key values of the object to which changes must be applied."
 
Ok, to solve this I had to instantiate again the entity and apply the current values.
 

tbl_Alias_Node t;

using (OMCMSNET_Entities db = new OMCMSNET_Entities())

{

t = db.tbl_Alias_Node.Single(tbl => tbl.id == 1);

t.alias = "myAlias";

}

using (OMCMSNET_Entities db = new OMCMSNET_Entities())

{

tbl_Alias_Node newT = db.tbl_Alias_Node.Single(tbl => tbl.id == 1);

db.tbl_Alias_Node.ApplyCurrentValues(t);

db.SaveChanges();

}

 
Magicaly it works although it has no sense.
 
If someone has any coherent explanation about this, please I'll be glad to learn about the microsoft way.
 
thanks in advance.
 
 
Adding JQuery to your Sharepoint
 
By providing the contents for the AdditionalPageHead Delegate Control that is used by all the out-of-the-box master pages, you can make sure the the jQuery library is loaded by all the SharePoint pages. The AdditionalPageHead Delegate Control allows multiple controls to provide contents, so it’s a great extensibility scenario. To accomplish this you need to build a web user control (ASCX file), that contains the script tag to load the jQuery library:

<%@ Control Language="VB" ClassName="jQueryControl" %>
<script type="text/javascript" src="http://weblogs.asp.net/_layouts//jquery-1.2.6.min.js"></script>

There is no code-behind file required. This control needs to be deployed to the C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES folder on the hard drive of every SharePoint Front End Web Server. Additionally you need to have a feature that will add the control to the AdditionalPageHead Delegate Control, the feature’s manifest will look like this (assuming the control is named jQueryControl.ascx):

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Control
    Id="AdditionalPageHead"
    ControlSrc="~/_controltemplates/jQueryControl ascx />
</Elements>

The feature can be scoped to any level, when it’s activated on a certain level, all the pages will automatically have the script tag in their HEAD tags. Pretty cool, isn’t it?

via: http://weblogs.asp.net/jan/archive/2008/11/20/sharepoint-2007-and-jquery-1.aspx

Personalize Your Portal with User Controls and Custom Web Parts
 

[Personalizable,

WebBrowsable,

WebDisplayName("Display Name"),

WebDescription("Description"),

Category("Configuration Category")]

1 - 10 Next

 ‭(Hidden)‬ Admin Links