I have grid-view in Windows Application. Now i want to display the shared document field values into grid-view. Can anybody have solutions????
IEnumerable<Sp.ListItem> list;
Sp.ClientContext spcontext = new ClientContext("http://Sharepointsite");
Sp.Web spsite = spcontext.Web;
Sp.ListCollection lcollection = spsite.Lists;
var productlist = spcontext.Web.Lists.GetByTitle("Shared Documents/Photo");
Sp.CamlQuery cm = new CamlQuery();
IQueryable<Sp.ListItem> mylist = productlist.GetItems(cm);
list = spcontext.LoadQuery(mylist);
spcontext.ExecuteQuery();
var qry = (from prd in list
select new
{
Name = prd.FieldValues.Values.ElementAt(1).ToString(),
Custom = prd.FieldValues.Values.ElementAt(2).ToString(),
}).ToList();
dataGridView1.DataSource = qry;
Error: List 'Shared Documents/Photo' does not exist at site with URL in Sharepointsite
Assuming that Photo is a Folder in your Document Library you can't take it like a List Title.
if you change your empty Caml Query to
var productlist = spcontext.Web.Lists.GetByTitle("Shared Documents");
var folderName = "Photo";
Sp.CamlQuery cm = new Sp.CamlQuery();
cm.ViewXml = "<View Scope=\"RecursiveAll\"> " +
"<Query>" +
"<Where>" +
"<And>" +
"<Eq>" +
"<FieldRef Name=\"FSObjType\" />" +
"<Value Type=\"Integer\">1</Value>" +
"</Eq>" +
"<Eq>" +
"<FieldRef Name=\"Title\"/>" +
"<Value Type=\"Text\">" + folderName + "</Value>" +
"</Eq>" +
"</And>" +
"</Where>" +
"</Query>" +
"</View>";
It will fetch all Folder in the Document Library which have that Name.
Now if you want a List of the FieldValue you can change your LinQ Query to something like this:
var qry = (from prd in list.ElementAt(0).FieldValues
select new
{
Key = prd.Key,
Value = prd.Value
}).ToList();
And now you have a collection with all Field Names and their Values. Which can be sorted/filtered what ever.
Edit:
If you want to select only some Fields of the collection one opportunity is to add a where clause to your linq query:
var qry = (from prd in list.ElementAt(0).FieldValues
where prd.Key == "Title"
select new
{
Key = prd.Key,
Value = prd.Value
}).ToList();
Error itself suggesting that problem with this line
var productlist = spcontext.Web.Lists.GetByTitle("Shared Documents/Photo");
Related
I work on an online search project
I want to make a search textbox that works like: if I want to search about a book that Joe wrote it with title my book and publisher is tia.
I type in the search: joe my book tia or tia jo book >
so I will get a result for it.
tia is from a table in SQL database
joe is from a table in SQL database
my book is from a table in SQL database
can somebody help me?
You can easily accomplish that if you add another column, that will contain concatenated data from other three columns, to your data table (in your database) and then make a search in that column.
writer title publisher search_column
joe my book tia joe my book tia
Then, you can make SQL query to search by that column with LIKE
example with ExecuteReader.
var query = "select * from my_table where 1 = 1 " + filterQuery;
Create parameters:
public static SqlParameter AddSqlParameter(string parameterName, object value)
{
var p = new SqlParameter(parameterName, value);
return p;
}
List<SqlParameter> sqlParameters = new List<SqlParameter>();
var filterQuery = "";
this will split your search input by spaces
string[] words = searchInput.Split(' ');
loop through your search phrases and add one parameter for each phrase found:
for (int i = 0; i < words.Count; i++) {
sqlParameters.Add(AddSqlParameter("#p" + i.ToString(), words[i]));
filterQuery = filterQuery + " AND search_column LIKE " + "#p" + i.ToString();
}
add your search query and parameters to ExecuteReader:
public static List<T> ExecuteReader<T>(string commandText, List<SqlParameter> parameters) where T : new()
{
List<T> output = new List<T>();
using (SqlConnection con = new SqlConnection(mySetting.ConnectionString))
using (SqlCommand cmd = new SqlCommand(commandText, con))
{
cmd.Parameters.AddRange(parameters.ToArray());
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
T t = new T();
for (int i = 0; i < rdr.FieldCount; i++)
{
Type type = t.GetType();
PropertyInfo prop = type.GetProperty(rdr.GetName(i));
if (prop != null)
{
prop.SetValue(t, rdr.GetValue(i) is DBNull ? null : rdr.GetValue(i), null);
}
}
output.Add(t);
}
return output;
}
}
}
call your ExecuteReader like this:
var result = ExecuteReader<myClass>(query, sqlParameters );
If you have further questions, just ask.
i have to read rows of data from an excel file which has only a column and then i have to save the rows in a table in database .
In my project i have to use ClosedXML .dll .
I have search but i couldn't find an example .
Can you please help me?
Thanks
For the ClosedXML part, you can refer to the documentation at https://github.com/ClosedXML/ClosedXML/wiki/Finding-and-extracting-the-data
private static void Main()
{
List<String> categories;
List<String> companies;
ExtractCategoriesCompanies("NorthwindData.xlsx", out categories, out companies);
// Do something with the categories and companies
}
private static void ExtractCategoriesCompanies(string northwinddataXlsx, out List<string> categories, out List<string> companies)
{
categories = new List<string>();
const int coCategoryId = 1;
const int coCategoryName = 2;
var wb = new XLWorkbook(northwinddataXlsx);
var ws = wb.Worksheet("Data");
// Look for the first row used
var firstRowUsed = ws.FirstRowUsed();
// Narrow down the row so that it only includes the used part
var categoryRow = firstRowUsed.RowUsed();
// Move to the next row (it now has the titles)
categoryRow = categoryRow.RowBelow();
// Get all categories
while (!categoryRow.Cell(coCategoryId).IsEmpty())
{
String categoryName = categoryRow.Cell(coCategoryName).GetString();
categories.Add(categoryName);
categoryRow = categoryRow.RowBelow();
}
// There are many ways to get the company table.
// Here we're using a straightforward method.
// Another way would be to find the first row in the company table
// by looping while row.IsEmpty()
// First possible address of the company table:
var firstPossibleAddress = ws.Row(categoryRow.RowNumber()).FirstCell().Address;
// Last possible address of the company table:
var lastPossibleAddress = ws.LastCellUsed().Address;
// Get a range with the remainder of the worksheet data (the range used)
var companyRange = ws.Range(firstPossibleAddress, lastPossibleAddress).RangeUsed();
// Treat the range as a table (to be able to use the column names)
var companyTable = companyRange.AsTable();
// Get the list of company names
companies = companyTable.DataRange.Rows()
.Select(companyRow => companyRow.Field("Company Name").GetString())
.ToList();
}
EDIT: The below only gets you a populated datatable. You'll then need to load that datatable into your database. You don't say which database this is, but for SQL Server you would use the SqlBulkCopy class (see definition, which also has an example).
Late to the party, but try this:
public static DataTable GetDataTableFromExcel(string path, string sheetname = "", bool hasHeader = true)
{
using (var workbook = new XLWorkbook(path))
{
IXLWorksheet worksheet;
if (string.IsNullOrEmpty(sheetname))
worksheet = workbook.Worksheets.First();
else
worksheet = workbook.Worksheets.FirstOrDefault(x => x.Name == sheetname);
var rangeRowFirst = worksheet.FirstRowUsed().RowNumber();
var rangeRowLast = worksheet.LastRowUsed().RowNumber();
var rangeColFirst = worksheet.FirstColumnUsed().ColumnNumber();
var rangeColLast = worksheet.LastColumnUsed().ColumnNumber();
DataTable tbl = new DataTable();
for (int col = rangeColFirst; col <= rangeColLast; col++)
tbl.Columns.Add(hasHeader ? worksheet.FirstRowUsed().Cell(col).Value.ToString() : $"Column {col}");
Logger("started creating datatable");
rangeRowFirst = rangeRowFirst + (hasHeader ? 1 : 0);
var colCount = rangeColLast - rangeColFirst;
for (int rowNum = rangeRowFirst; rowNum <= rangeRowLast; rowNum++)
{
List<string> colValues = new List<string>();
for (int col = 1; col <= colCount; col++)
{
colValues.Add(worksheet.Row(rowNum).Cell(col).Value.ToString());
}
tbl.Rows.Add(colValues.ToArray());
}
Logger("finished creating datatable");
return tbl;
}
}
and call like this:
var datatable = GetDataTableFromExcel(fileName, sheetName);
If you're using (the excellent and free in its basic form) LinqPad, you can inspect the datatable using datatable.Dump();
I am inserting data in the sql server.Here is the code:
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter();
param[0].ParameterName = "#Exch";
param[0].SqlDbType = SqlDbType.Int;
param[0].Value = "BSE";
formObjSqlConnection.SQLConnection.Executes("LPExch..DeleteVarMargin", param);
foreach (BseVar objBseVar in objListNseData)
{
currentIndex++;
param = new SqlParameter[10];
param[0] = new SqlParameter();
param[0].ParameterName = "#Exch";
param[0].SqlDbType = SqlDbType.Char;
param[0].Value = "BSE";
param[1] = new SqlParameter();
param[1].ParameterName = "#Symbol";
param[1].SqlDbType = SqlDbType.Char;
param[1].Size = 10;
param[1].Value = objBseVar.Symbol;
param[2] = new SqlParameter();
param[2].ParameterName = "#Series";
param[2].SqlDbType = SqlDbType.Char;
param[2].Value = "EQ";
param[3] = new SqlParameter();
param[3].ParameterName = "#SecurityVar";
param[3].SqlDbType = SqlDbType.SmallMoney;
param[3].Value = objBseVar.SecurityVar;
param[4] = new SqlParameter();
param[4].ParameterName = "#IndexVar";
param[4].SqlDbType = SqlDbType.SmallMoney;
param[4].Value = 0;
param[5] = new SqlParameter();
param[5].ParameterName = "#VarMargin";
param[5].SqlDbType = SqlDbType.SmallMoney;
param[5].Value = objBseVar.IndexVar;
param[6] = new SqlParameter();
param[6].ParameterName = "#AdhocMargin";
param[6].SqlDbType = SqlDbType.SmallMoney;
param[6].Value = objBseVar.SecurityVar - objBseVar.IndexVar;
param[7] = new SqlParameter();
param[7].ParameterName = "#VarMarginRate";
param[7].SqlDbType = SqlDbType.SmallMoney;
param[7].Value = objBseVar.IndexVar;
formObjSqlConnection.SQLConnection.Executes("LPExch..UpdateOrAddCashVarMarginBSE", param);
if (Convert.ToInt32(1 / progressChange * currentIndex) <= 100)
objImportMaster.UpdateProgressBar(Convert.ToInt32(1 / progressChange * currentIndex));
}
formObjSqlConnection.SQLConnection.Executes("LPExch..UpdateCashVarMarginBSEScripNo");
Is there any other way i can insert the data in the database.The problem is that database is taking too much time to insert the data.Also i am updating the progressbar in other UI.
Is that the reason for slow insertion?
Can we use any other way to insert data.?
Right now you are sending every insert one at a time. That's slow. If you can change the database, look up table valued parameters and pass a table to your function so you can send all the records just once.
If you have direct access to a table, you can also use bulk copy.
If you are trying to insert many records then consider using bulk copy, it is quite fast.
An example is available here.
private void LoadData()
{
MedicalCustomersDBEntities db = new MedicalCustomersDBEntities();
CustomerList = db.Customers;
AutoCompleteStringCollection completeSource = new AutoCompleteStringCollection();
completeSource.AddRange(CustomerList.Select(ar => " " + ar.FirstName).ToArray());
completeSource.AddRange(CustomerList.Select(ar => ar.FirstName).ToArray());
this.AutoCompleteMode = AutoCompleteMode.Suggest;
this.AutoCompleteSource = AutoCompleteSource.CustomSource;
this.AutoCompleteCustomSource = completeSource;
}
I use this code to load all my customers. But when I have two customers with the same name the autocomplete textbox make distinct for result.
Is there a way to show all result.
Why don't you make use of distinct in the query itself.
CustomerList = db.Customers.Name.Distinct();
I don't have a PC, but you can try something like that....The above code is not right
I have a RIA service that is to return a list of schools and populate a datagrid. This datagrid is duplicating the first result throughout the entire grid, as opposed to showing each item from source in its own row.
The service is as follows
var schools1 = (from i in DataContext.PrevSchools
join skl in DataContext.SchoolLists on i.School_id equals skl.School_Id
where i.Email_Address == email
select new PreviousSchools
{
PrevSchoolsId = i.PrevSchools_id,
AppEmail = i.Email_Address,
SchoolId = i.School_id,
DateAttended = i.YearsAttended,
Study = i.Study,
Credit = i.Credit,
CompleteStatus = i.Complete_Status,
Award = i.Award,
SchoolName = skl.School_name
}).Union(from i in DataContext.PrevSchools
join skl1 in DataContext.Schools on i.School_id equals skl1.School_id
where i.Email_Address == email && i.School_type_id == 1
select new PreviousSchools
{
PrevSchoolsId = i.PrevSchools_id,
AppEmail = i.Email_Address,
SchoolId = i.School_id,
DateAttended = i.YearsAttended,
Study = i.Study,
Credit = i.Credit,
CompleteStatus = i.Complete_Status,
Award = i.Award,
SchoolName = skl1.School_name
}).OrderBy(q => q.SchoolName);
return schools1;
The Databinding is:
this.PrevSchools.prevSchoolDataGrid.DataContext = SchoolsList;
The SchoolList is an ObservableCollection, it was set as a list and also a, IEnumerable, and it still yielded the duplicated results.
Fixed it, it was an error in the Model class, the key was set to the wrong property