I have created event receiver with C# coding in SharePoint.when item should match is already have. it showing massage like this is my code..
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
SPList oList = null;
string strCarName = string.Empty;
using (SPWeb web = properties.Web)
{
oList = web.Lists["Cars"];
string dropdwnvalue = web.Lists[properties.ListId].Fields["CarName"].InternalName;
String lookupFieldStringValue = Convert.ToString(properties.AfterProperties[dropdwnvalue]);
SPListItem item = oList.Items[Convert.ToInt32(lookupFieldStringValue) - 1];
strCarName = Convert.ToString(item["LinkTitle"]);
}
string strStartdate = Convert.ToString(properties.AfterProperties["EventDate"]);
SPQuery existingItemsQuery = new SPQuery();
existingItemsQuery.Query = "<Where><And><Eq><FieldRef Name='EventDate'/><Value Type='DateTime'>" + strStartdate + "</Value></Eq><Eq><FieldRef Name='Car_x0020_Name'/><Value Type='Lookup'>" + strCarName + "</Value></Eq></And></Where>";
SPListItemCollection existingItems = properties.List.GetItems(existingItemsQuery);
if (existingItems.Count >= 1)
{
properties.Cancel = true;
properties.ErrorMessage = "Item is already exists";
properties.Status = SPEventReceiverStatus.CancelWithError;
// ClientScript.RegisterStartupScript(typeof(Page), "test", "<script>alert('Hello');return false;</script>");
}
output:-
item is already exists.
that item adding only one time in a day.again i cant add another item. But i want add another item in a day change time
any one can help me out.
As I can see, you have problem with the query string, you should use this:
existingItemsQuery.Query = "<Where><And><Eq><FieldRef Name='EventDate'/><Value Type='DateTime' IncludeTimeValue='TRUE'>" + strStartdate + "</Value></Eq><Eq><FieldRef Name='Car_x0020_Name'/><Value Type='Lookup'>" + strCarName + "</Value></Eq></And></Where>";
and you should have strStartdate with format like this '1971-01-01T00:00:00Z'
you can use this method:
SPUtility.CreateISO8601DateTimeFromSystemDateTime(properties.AfterProperties["EventDate"])
Hope this helps!
Not sure that you can register script because the page will be redirected.
But you can use properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl and add custom parameter to query string. Also script must be always on the page.
So you just check necessary parameter in QS and show alert if it is present.
Related
I created a visual web part and loading the list in Grid. Now when User A login it has to display only the items which are created by user A. USER B it has to display only the items that belong to USER b. Here is the code which i have written.It Display all the items irrespective of the logged in user. Can any one help me on this
public void Displaylistdata()
{
// System.Diagnostics.Debugger.Break();
DataTable dt = new DataTable();
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["Participation at a Glance"];
string strCreatedby = SPContext.Current.Web.Author.Name;
SPQuery oQuery = new SPQuery();
oQuery.Query = "<Query><Where><Eq><FieldRef Name='Author' /><Value Type='User'>" + strCreatedby + "</Value></Eq></Where></Query>";
SPListItemCollection collListItems = oSpList.GetItems(oQuery);
DataTable dts = collListItems.GetDataTable();
if (dts != null)
{
Gridview1.GridLines = GridLines.None;
Gridview1.DataSource = dts;
Gridview1.DataBind();
Controls.Add(Gridview1);
}
else`enter code here`
{
lbl_noact.Visible = true;
lbl_noact.Text = "We apologize there are no times currently available.";
}
}
Hi I have fixed by changing my Camel query as below. Previously the data type is USER but when i changed to string it works like a charm :-)
DataTable dt = new DataTable();
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["Participation at a Glance"];
string strCreatedby = SPContext.Current.Web.CurrentUser.Name;
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Eq><FieldRef Name='Author' /><Value Type='String'>" + strCreatedby + "</Value></Eq></Where>";
SPListItemCollection collListItems = oSpList.GetItems(oQuery);
I have a list named "Designation" that contains a Designation Code and Designation Name.
I have another list named "Employee" that contains Employee Name and Designation Name (as a Lookup Field).
I am able to insert values to "Employee" list using the following code.
protected void AddEmp(object sender, EventArgs e)
{
string emp_name = txtEmployeeName.Text;
string emp_designation = ddlDesignation.SelectedValue;
using (SPSite site = new SPSite("My Site"))
{
using (SPWeb web = site.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
web.AllowUnsafeUpdates = true;
SPList splist_employees = web.Lists["Employee"];
SPList splist_designations = web.Lists["Designations"];
SPListItemCollection splc_items = splist_employees.Items;
SPListItem spli_item = splc_items.Add();
SPFieldLookup lookup = splist_employees.Fields["Designated"] as SPFieldLookup;
string fieldName = lookup.LookupField;
spli_item["Employee Name"] = emp_name;
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations);
spli_item.Update();
});
}
}
}
public static string GetLookFieldIDS(string lookupValues, SPList lookupSourceList)
{
string id = string.Empty;
SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection();
SPQuery query = new Microsoft.SharePoint.SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Designation' /><Value type='Text'>"+lookupValues + "</Value></Eq></Where>";
SPListItemCollection listItems = lookupSourceList.GetItems(query);
foreach (Microsoft.SharePoint.SPListItem item in listItems)
{
id = item.ID.ToString();
}
return id;
}
Here I have given the field name as 'Designation' inside the query.
But, I want to find the field name based on the value given from the user end instead of hard-coding the field name as 'Designation'.
Any help is greatly appreciated. Thanks in advance.
Not sure about your request but, you could pass SPFieldLookup.LookupField property to your GetLookFieldIDS method and use that variable instead of "Designation"
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations, lookup.LookupField);
I have two lists and one event receiver. The event receiver sets a column of the list to a unique identifier (combo of the content type and the item id).
In the other list I use query string and the newform to set a field to the very same unique identifier above. I also gather some more info in that newform I want to work with.
How can I query a list without knowing the ID, but I have another unique id to single out from the other items so I can work with it just as SPitem firstitem below so I can find the other fields.
Getting my first item to get the unique title:
SPSite currentSite = SPContext.Current.Site;
SPWeb web = currentSite.OpenWeb();
string queryString = Request.QueryString["uniqueID"];
SPList firstList = web.Lists["My First List"];
SPItem firstItem = firstList.Items.GetItemById(Convert.ToInt32(queryString));
this is the unique title I want to query second list with:
string uniqueTitle = firstItem["Title"].ToString();
getting my second list up, ready for action:
SPList secondList = web.Lists["My Second List"];
Thanks
ANSWER:
// open the second list
SPList secondList = web.Lists["My Second List"];
// Query the second list for the item
SPQuery myQuery = new SPQuery();
myQuery.Query = "<Where><Eq><FieldRef Name = \"Title\"/>" +
"<Value Type = \"Text\">" + uniqueTitle +
"</Value></Eq></Where>";
// Get a collection of the second list items selected by the query and pick the first (0) value as it should only return one!
SPListItemCollection secondlistItemCol = secondList.GetItems(myQuery);
SPListItem secondItem = secondlistItemCol[0];
You will want to use the GetItems command with an SPQuery object. It is not too complex to sort out with the MS code example below.
using System;
using Microsoft.SharePoint;
namespace Test
{
class ConsoleApp
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
// Build a query.
SPQuery query = new SPQuery();
query.Query = string.Concat(
"<Where><Eq>",
"<FieldRef Name='Status'/>",
"<Value Type='CHOICE'>Not Started</Value>",
"</Eq></Where>",
"<OrderBy>",
"<FieldRef Name='DueDate' Ascending='TRUE' />",
"<FieldRef Name=’Priority’ Ascending='TRUE' />",
"</OrderBy>");
query.ViewFields = string.Concat(
"<FieldRef Name='AssignedTo' />",
"<FieldRef Name='LinkTitle' />",
"<FieldRef Name='DueDate' />",
"<FieldRef Name='Priority' />");
query.ViewFieldsOnly = true; // Fetch only the data that we need.
// Get data from a list.
string listUrl = web.ServerRelativeUrl + "/lists/tasks";
SPList list = web.GetList(listUrl);
SPListItemCollection items = list.GetItems(query);
// Print a report header.
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
"Assigned To", "Task", "Due Date", "Priority");
// Print the details.
foreach (SPListItem item in items)
{
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);
}
}
}
Console.ReadLine();
}
}
}
I need to get GUID of an item. I know the SiteURL, List Name and Item Name. How do I get guid of this item insead to using splistitem li in list.items and loop through each item (if li.name==myitemname then assign strguid=li.uniqueid.tostring()
Is there a way not to use foreach loop since I know the name of the item? This will save time to loop throught items.
If you are creating a spquery on your unique item in splistcollection you would be returned only one element which you can obtain without foreach
using (SPSite site = new SPSite(SiteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList apps = web.GetList(web.Url + "/Lists/MyList");
SPQuery query = new SPQuery();
query.Query = String.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='String'>{0}</Value></Eq></Where>", _title);
items = apps.GetItems(query);
if(items.Count > 0)
{
Guid id = items[0].UniqueId;
}
}
}
Works but I have 11 files and they all have the same file name "license.txt" and they are in the same document library. 1 file "license.txt" is under the root document library and other 10 in 10 different folders within a document library. so what if i am looking for the license.txt file that's in Demo folder?
This code works but only finds license.txt under the root.
private void btnGetFileGuid_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
{
using (SPWeb web = site.OpenWeb())
{
SPList spList = web.Lists["Auto Cad"];
string fileName = "license.txt";
SPQuery query = new SPQuery();
query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
SPListItemCollection items = spList.GetItems(query);
if (items.Count > 0)
{
Guid id = items[0].UniqueId;
lblGuid.Text = id.ToString();
}
}
}
}
Trying the following and it seems to be working.
query.ViewAttributes = "Scope=\"Recursive\"";
or
query.ViewAttributes = "Scope='RecursiveAll'";
the items.count should be atlease 10. I have 10 subfolders (Release 1 ..... Release 10) with in this documnent library "Auto Cad" and each subfolder has a file called license.txt. hmmm
Why this is not returning any file(s)?
private void btnGetFileGuid_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
{
using (SPWeb web = site.OpenWeb())
{
SPList spList = web.Lists["Auto Cad"];
string fileName = "license.txt";
SPQuery query = new SPQuery();
query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
SPListItemCollection items = spList.GetItems(query);
if (items.Count > 0)
{
Guid id = items[0].UniqueId;
lblGuid.Text = id.ToString();
}
}
}
}
SPQuery only searches a particular folder - to recursively search through subfolders you need to set
SPQuery.ViewAttributes = "Scope=\"Recursive\"";
So your code should be
SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\"";
query.Query=".... REST OF YOUR CODE HERE "
query.Query="" + fileName + "";
This line is wrong. This should be CAML query and not name of filename.
You need to make a recursive call use the solution provided in question link provided below
i would recommend use qry.ViewAttributes = "Scope='RecursiveAll'"; to get documents and folders as well
query to get all items in a list including items in the sub folders in sharepoint