C# Retrieve Document List From SharePoint 2013 Document Library - c#

I want to make this really simple. I have a fresh, brand new asp.net C# web form with the code behind showing as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
I have a SharePoint 2013 site with a document library that has a few documents in it with a few columns of metadata.
How do I make it show on the web page, a link to each document and the metadata from the columns for each document from the library. I'm super new to any work with integrating SharePoint and ASP.Net.
Please help.
Andy

Sharepoint has 3 APIs that you could use. Have a look here: https://msdn.microsoft.com/en-us/library/office/jj164060.aspx
You probably want to use the client.svc service via the CSOM Library (Microsoft.SharePoint.Client) just because it is the easiest to get up and running on. Don't use the older asmx api because it is deprecated. There's a third option - REST - but it doesn't provide all the functionality that CSOM does.
Here's some rough code showing the basics. There are a lot of nuances that aren't covered in the code (SharePoint is complicated) so you you'll also want to find some additional information online.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Client;
public partial class _Default : System.Web.UI.Page
{
protected string SiteUrl = "http://mysite.mydomain.com/site";
protected string LibraryName = "MyList";
protected void Page_Load(object sender, EventArgs e)
{
var context = new ClientContext(SiteUrl);
context.Load(context.Site);
context.ExecuteQuery();
var list = context.Web.Lists.GetByTitle(LibraryName);
if (list == null)
{
throw new ArgumentException(string.Format("List with name '{0}' not found on site '{1}'", LibraryName, SiteUrl));
}
context.Load(list, l => l.RootFolder.ServerRelativeUrl);
context.ExecuteQuery();
// Empty query. You probably want to filter on something so
// do a search on "CAML Query". Also watch out for SharePoint
// List View Threshold which limits # of items that can be retrieved
var camlQuery = #"<View Scope='All'><Query></Query></View>";
var items = list.GetItems(camlQuery);
context.Load(items, l => l.IncludeWithDefaultProperties(i => i.Folder, i => i.File, i => i.DisplayName));
context.ExecuteQuery();
// Url for first item
var url = SiteUrl + "/" + LibraryName + "/" + items[0]["Title"]
}
}

Related

Class in ASP.NET Partial Class in App_Code

I created a class for connection and using with register.aspx without any problem. When i try to move codes from register.aspx.cs to regpartial.cs then i get an conflict error: "connection conn = new connection();"
I would like to move codes register.aspx.cs to mypartial.cs. I think it will be better but i'm not sure how can i solve conflict problem.
Register.aspx.cs (final)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using test.App_Code;
namespace test
{
public partial class register: System.Web.UI.Page
{
private void Page_Load(object sender, EventArgs e)
{
}
Connection.cs (final try)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
namespace test.App_Code
{
public class connection
{
public SqlConnection connect()
{
SqlConnection conn= new SqlConnection("Data Source=******;Initial Catalog=****;Integrated Security=False;User Id=****;Password=*****;MultipleActiveResultSets=True");
baglanti.Open();
return (conn);
}
}
regpartial.cs (Final try)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace test.App_Code.partials
{
connection conn = new connection();
public partial class regpartial : register
{
}
}
In general you shouldn't have much code inside your aspx.cs files.
You want to separate the logic that is directly your view/presentation logic (stuff that makes the .aspx pages work) from your business logic (sequencing, transformation, validation), and finally you want to have your Data Access / Resource Access to be isolated.
I'd also recommend using Dapper.NET over raw ADO.NET/SqlConnection.
I'm going to string together a very basic example of how you can separate this. This is not guaranteed to compile c# code but it will very close pseudocode.
Inside registration.aspx.cs
private void btnRegister_Click(object sender, EventArgs e)
{
var email = txtEmail.Text;
var password = txtPassword.Text;
var registration = new Registration { Email = email, Password = password }
var bizService = new RegistrationService();
var response = bizService.Register(registration);
if(response.Success) Response.Redirect("~/registration/success");
ltlError.Text = response.FailureMessage;
}
RegistrationService.cs
public class RegistrationService {
public RegistrationResponse Register(Registration req)
{
var regDAL = new RegistrationAccess();
var isEmailDuplicated = regDal.DoesEmailExist(req.Email)
if(isEmailDuplicated)
return new RegistrationResponse {
Success = false,
FailureMessage = "Email exists, did you mean to login instead?
}
regDAL.InsertNewRegistration(req)
return new RegistrationResponse { Success = true };
}
}
Lastly you should have a RegistrationAccess.cs that contains only code for reading and writing to SQL Server / other database / file system.
Note how the aspx.cs file has no knowledge of RegistrationAccess. Your view should not be directly calling the database. The other thing to note is that RegistrationService has no knowledge of the view. It receives a Registration type, then executes business logic and calls out to the DAL. The DAL class will have zero knowledge of both the view and the RegistrationService, it will know only one thing, the database.
This is the basis of a very simple ASP.NET webforms solution. A better solution would use the MVP/MVVM patterns and the Dependency Inversion Principle but those aren't worth using if you don't understand basic separation of concerns yet.

export IDM download list using C#

I have to make a program to back up my IDM download list every day, because there is other ones using my computer and they removing my download list.
IDM API only lets me add download to IDM list, so is there any library or other way to back up my IDM download list using C#?
thanks for helping
Thanks to #Setsu found out a solution. there is a key in registry which contains all of the URLs. the key is HKEY_CURRENT_USER\Software\DownloadManager and it contains keys which contains values named Url0 with the URL in it.
As an example HKEY_CURRENT_USER\Software\DownloadManager\85\Url0 contains one of added link to IDM download list.
So I searched all of the HKEY_CURRENT_USER\Software\DownloadManager subkeys for Url0 and saved the values to a list box using this code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace IDMListSaver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\DownloadManager");
string[] keys = key.GetSubKeyNames();
for (int i = 0; i <= key.SubKeyCount-1; i++)
{
key = key.OpenSubKey(keys[i]);
Object o = key.GetValue("Url0");
if (o != null)
{
listBox1.Items.Add(o);
}
key = Registry.CurrentUser.OpenSubKey("Software\\DownloadManager");
}
}
}
}
It definitely can get better, but it solved my problem until here.
So thanks again #Setsu

Error Message is not clear to me

i Keep getting this error message and can't figure out why?
Compiler Error Message: CS1513: } expected
here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void gettickvalue(object sender, EventArgs e)
{
Random RandomNumber = new Random();
int n = RandomNumber.Next(1, 9);
imgBanner.ImageUrl = System.String.Concat("Timer/banner_", n.ToString(), ".jpg");
}
If what you posted is your whole class, you're missing a curly brace. Exactly as the error message says.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void gettickvalue(object sender, EventArgs e)
{
Random RandomNumber = new Random();
int n = RandomNumber.Next(1, 9);
imgBanner.ImageUrl = String.Concat("Timer/banner_", n.ToString(), ".jpg");
}
} //we added this curly brace
It's easier to see where it's missing if you format your code properly. Visual Studio can do this for you, look it up to see how in your version. I'm on Visual Studio 2010 Pro, so I go to Edit -> Advanced -> Format Document.
Notice also that I changed your concatenation function to just be String.Concat instead of System.String.Concat. No need to put the system reference in front of it because the namespace is already referenced by your first using statement.
I also suggest you rename your function. See General Naming Conventions on MSDN.

How do I use the Bing Search API in Windows Phone?

I'm trying to use the Bing Search API to find images as backgrounds to the tiles inside of my app. I've included the BingSearchContainer.cs in my Project but I can't make it work with the sample code provided here.
Any guidelines for how to use the Bing Search API inside of my Windows Phone 8 app would be appriciated!
Thanks for any answer.
I expect that you already have a AccountKey so I wont tell you have to get one.
Implementation
First of all, add the BingSearchContainer.cs to your project
Implement the sample C# code found in the Bing API Quick Start & Code
Thereafter, right-click References and choose Manage NuGet Packages... and search for, and install, Microsoft.Data.Services.Client.WindowsP.
Modify the sample code so that it work with Windows Phone:
using Bing;
using System;
using System.Data.Services.Client;
using System.Linq;
using System.Net;
namespace StackOverflow.Samples.BingSearch
{
public class Finder
{
public void FindImageUrlsFor(string searchQuery)
{
// Create a Bing container.
string rootUri = "https://api.datamarket.azure.com/Bing/Search";
var bingContainer = new Bing.BingSearchContainer(new Uri(rootUri));
bingContainer.UseDefaultCredentials = false;
// Replace this value with your account key.
var accountKey = "YourAccountKey";
// Configure bingContainer to use your credentials.
bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);
// Build the query.
var imageQuery = bingContainer.Image(query, null, null, null, null, null, null);
imageQuery.BeginExecute(_onImageQueryComplete, imageQuery);
}
// Handle the query callback.
private void _onImageQueryComplete(IAsyncResult imageResults)
{
// Get the original query from the imageResults.
DataServiceQuery<Bing.ImageResult> query =
imageResults.AsyncState as DataServiceQuery<Bing.ImageResult>;
var resultList = new List<string>();
foreach (var result in query.EndExecute(imageResults))
resultList.Add(result.MediaUrl);
FindImageCompleted(this, resultList);
}
public event FindImageUrlsForEventHandler FindImageUrlsForCompleted;
public delegate void FindImageUrlsForEventHandler(object sender, List<string> result);
}
}
Example
And now, let's use the code I provided you with:
using Bing;
using System;
using System.Data.Services.Client;
using System.Linq;
using System.Net;
namespace StackOverflow.Samples.BingSearch
{
public class MyPage
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var finder = new Finder();
finder.FindImageUrlsForCompleted += finder_FindImageUrlsForCompleted;
finder.FindImageUrlsFor("candy");
}
void finder_FindImageUrlsForCompleted(object sender, List<string> result)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
foreach (var s in result)
MyTextBox.Text += s + "\n";
});
}
}
}

using Microsoft Translate ( GetTranslation Service )

I'm going to build website that uses the translation service from Microsoft. I need to get all the available translations for each word but the code I have provides only one translation while it is supposed to give all available translations. Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using microsofttranslator;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.ServiceModel;
using TranslatorService;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{string Appid="my Appid";
string t="any text";
microsofttranslator.TranslateOptions options = new microsofttranslator.TranslateOptions();
options.Category = "general";
options.ContentType = "text/plain";
options.User = "TestUserId";
options.Uri = "";
bool a=true;
SoapService s = new SoapService();
microsofttranslator.GetTranslationsResponse translations = s.GetTranslations(Appid, t, "ar", "en", 5,a, options);
Response.Write(string.Format("Available translations for source text '{0}' are", t));
foreach (microsofttranslator.TranslationMatch translationMatch in translations.Translations)
{
Response.Write(string.Format("Translated text: {0}" + Environment.NewLine + " Rating:{1}" + Environment.NewLine + "Count:{2}" + Environment.NewLine, translationMatch.TranslatedText, translationMatch.Rating.ToString(), translationMatch.Count.ToString()));
} }}
I added Microsft translate WSDL as a web reference http://api.microsofttranslator.com/v2/Soap.svc?wsdl and I added TranslatorService as a service reference http://api.microsofttranslator.com/V2/Soap.svc
This code works well but as I said it gives only one translation while it is supposed to give all the available translations of a word. I cannot figure out what I am doing wrong.
Maybe you should use the "translateArray" method.
http://msdn.microsoft.com/en-us/library/ff512438.aspx

Categories