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
Comments enabled
Sorry for the delay, I've just enabled the comments in this blog :-) better late than ever
AsyncFileUpload + UpdatePanel + First load page
This is my code to upload a file in two steps.
 
- One: upload the file
 
-Two: Send the file to the server
 

<div>

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">

</asp:ToolkitScriptManager>

<asp:Timer ID="Timer1" runat="server" Interval="1" OnTick="GetData">

</asp:Timer>

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" EnableViewState="true">

<Triggers>

<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click"/>

<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />

</Triggers>

<ContentTemplate>

<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">

<ProgressTemplate>

<asp:Image runat="server" ID="imgLoader" ImageUrl="/images/ajax-loader.gif" />

</ProgressTemplate>

</asp:UpdateProgress>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server"

onuploadedcomplete="AsyncFileUpload1_UploadedComplete" />

<asp:FileUpload runat="server" ID="fu" />

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="btnUpload_Click"/>

<br />

<asp:Label ID="Label2" runat="server" />

</ContentTemplate>

</asp:UpdatePanel>

<br />

</div>

 

public HttpPostedFile postedFile

{

get

{

return Session["postedFile"] as HttpPostedFile;

}

set

{

Session.Add("postedFile", value);

}

}

protected void Page_Load(object sender, EventArgs e)

{

}

protected void btnUpload_Click(object sender, EventArgs e)

{

System.Threading.Thread.Sleep(5000);

Label1.Text = "You uploaded " + postedFile.FileName;

}

protected void GetData(object sender, EventArgs e)

{

Timer1.Enabled = false;

Label2.Text = DateTime.Now.ToString();

}

protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)

{

postedFile = AsyncFileUpload1.PostedFile;

}

 

Notes: OnUploadedComplete cannot be saved on the ViewState because it breaks the life cycle page. The UploadedComplete doesn't go to the SaveViewState Event nor Render. Thats because you cannot save the file in ViewState or update the server controls.

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;
        }
    }
}
 
1 - 10 Next

 ‭(Hidden)‬ Admin Links