ListViewWebPart - sharepoint

I'm using listviewwebpart to display contents of SPFolder (subfolder inside a list) to display its contents.
Beolw is the code to implement the same :
protected override void CreateChildControls()
{
try
{
base.CreateChildControls();
webPart = new ListViewWebPart();
using (var site = new SPSite(SPContext.Current.Web.Url))
using (var web = site.OpenWeb())
{
clientName = DataLogic.Client.GetClientName(Constants.Session.Client_ClientID);
var library = web.Lists["Account"];
webPart.ListName = library.ID.ToString("B").ToUpper();
webPart.ListId = library.ID;
SPFolder folder = web.GetFolder("/Account/" + clientName);
if (folder.Item != null)
{
SPContentTypeId folderctid = folder.Item.ContentType.Id;
//set the folder url
SetPrivateFieldValue(webPart, "rootFolder", folder.Url);
SetPrivateFieldValue(webPart, "folderCtId", folderctid.ToString());
webPart.ListViewXml = library.DefaultView.GetViewXml();
webPart.ChromeType = PartChromeType.None;
this.mainSec.Controls.Add(webPart);
}
else
{
lblWarning.Text = "There is no document library associated with client " + clientName;
}
}
}
catch (Exception ex)
{
}
}
private static void SetPrivateFieldValue(object obj, string fieldName, string val)
{
FieldInfo fi = obj.GetType().GetField(fieldName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
fi.SetValue(obj, val);
}
The contents display correctly but the toolbar is the parent list's toolbar and not the folder's toolbar.
How can i modify the toolbar context to load the context of the spfolder?

Related

how to attach an XML file in the "Files" tab of an action

I have a big question, you can attach XML through an action, when you import the XML and also save it in the "Files" tab, the question is. if it can be attached?.
Here is an example image:
what is missing is that I automatically attach in the "Files" tab, when I put upload
Here is my code where, I attached the XML
public PXAction<ARInvoice> CargarXML;
[PXUIField(DisplayName = "Carga de código hash")]
[PXButton()]
public virtual void cargarXML()
{
var Result = NewFilePanel.AskExt(true);
if (Result == WebDialogResult.OK)
{
PX.SM.FileInfo fileInfo = PX.Common.PXContext.SessionTyped<PXSessionStatePXData>().FileInfo["CargaSessionKey"];
string result = System.Text.Encoding.UTF8.GetString(fileInfo.BinData);
ARInvoice ari = Base.Document.Current;
xtFECodHashEntry graph2 = PXGraph.CreateInstance<xtFECodHashEntry>();
var pchExt = ari.GetExtension<ARRegisterExt>();
string Valor = "";
XmlDocument xm = new XmlDocument();
xm.LoadXml(result);
XmlNodeList elemList = xm.GetElementsByTagName("ds:DigestValue");
for (int i = 0; i < elemList.Count;)
{
Valor = (elemList[i].InnerXml);
break;
}
PXLongOperation.StartOperation(Base, delegate ()
{
xtFECodHash dac = new xtFECodHash();
dac.RefNbr = ari.RefNbr;
dac.DocType = ari.DocType;
dac.Nrocomprobante = ari.InvoiceNbr;
dac.Hash = Valor;
dac.Tipo = pchExt.UsrTDocSunat;
graph2.xtFECodHashs.Insert(dac);
graph2.Actions.PressSave();
});
}
}
If you have the FileInfo object which it seems like you do I have used something like this:
protected virtual void SaveFile(FileInfo fileInfo, PXCache cache, object row)
{
if (fileInfo == null)
{
return;
}
var fileGraph = PXGraph.CreateInstance<UploadFileMaintenance>();
if (!fileGraph.SaveFile(fileInfo, FileExistsAction.CreateVersion))
{
return;
}
if (!fileInfo.UID.HasValue)
{
return;
}
PXNoteAttribute.SetFileNotes(cache, row, fileInfo.UID.Value);
}
So in your example you could call this method as shown above using the following:
SaveFile(fileInfo, Base.Document.Cache, Base.Document.Current);

Upload Images to Serial Number

I have created a custom NOTEID field in InItemLotserial Table to upload images for each serial number in a custom page. It works fine without any issue.
I have wrote a processing page to update the images for existing serial numbers.
protected void AttachImage(InfoINItemLotSerialImport row, INItemLotSerial ser, InventoryItem itm)
{
string imageurl = row.ImageSourceUrl;
string imageType = row.ImageType;
string sRetVal = string.Empty;
if (itm != null)
{
if (ser != null)
{
try
{
WebClient wc = new WebClient();
byte[] buffer = wc.DownloadData(imageurl);
//MemoryStream ms = new MemoryStream(bytes);
string fileName = Path.GetFileName(imageurl);
fileName = string.Format("Serial Number attribute ({0} {1})\\{2}", itm.InventoryID, ser.LotSerialNbr, fileName);
PX.SM.FileInfo fileinfo = null;
PX.SM.UploadFileMaintenance filegraph = PXGraph.CreateInstance<PX.SM.UploadFileMaintenance>();
fileinfo = new PX.SM.FileInfo(fileName, null, buffer);
fileinfo.IsPublic = true;
if (filegraph.SaveFile(fileinfo))
{
ItemLotSerialMnt oLotSerMnt = PXGraph.CreateInstance<ItemLotSerialMnt>();
oLotSerMnt.lotserailrecdata.Current = ser;
oLotSerMnt.lotserial.Current = ser;
PXNoteAttribute.SetFileNotes(oLotSerMnt.lotserailrecdata.Cache, oLotSerMnt.lotserailrecdata.Current, fileinfo.UID.Value);
PXNoteAttribute.SetNote(oLotSerMnt.lotserailrecdata.Cache, oLotSerMnt.lotserailrecdata.Current, "");
sRetVal = fileinfo.Name;
}
}
catch
{
}
}
}
}
It uploads the data into UploadFile table and entry looks fine. I can access the image using the URL, but the same is not reflecting in file section of serial page.
How acumatica links the file with the screen?
Update 1
#region UsrNoteID
public abstract class usrNoteID : PX.Data.IBqlField
{
}
protected Guid? _UsrNoteID;
[PXNote()]
public virtual Guid? UsrNoteID
{
get
{
return this._UsrNoteID;
}
set
{
this._UsrNoteID = value;
}
}
#endregion
Accumatica support helped me to fix the issue. I have missed firing persist event to save.
if (filegraph.SaveFile(fileinfo))
{
ItemLotSerialMnt oLotSerMnt = PXGraph.CreateInstance<ItemLotSerialMnt>();
oLotSerMnt.lotserailrecdata.Current = ser;
oLotSerMnt.lotserial.Current = ser;
PXNoteAttribute.SetFileNotes(oLotSerMnt.lotserailrecdata.Cache, oLotSerMnt.lotserailrecdata.Current, fileinfo.UID.Value);
PXNoteAttribute.SetNote(oLotSerMnt.lotserailrecdata.Cache, oLotSerMnt.lotserailrecdata.Current, "");
sRetVal = fileinfo.Name;
oLotSerMnt.Persist();
}
oLotSerMnt.Persist();

Sharepoint list does not exist on the site efter but it exists in my code when debugging

I shall eventually create a sharepoint calendar. I want to create a eventslist here but I'll get this strange error here.
I create a a eventslist and then check [to see] if its already created. If it is, not I want to create it but then my testLabel says that its already exists.
When I try to delete the list, on the myButton_Click, it gives me this error:
Microsoft.SharePoint.Client.ServerException: List 'CompanyCalendar'
does not exist at site with URL 'http://server1'.
Code
using Microsoft.SharePoint.Client;
namespace CalendarWeb.Pages
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
{
Web web = clientContext.Web;
ListCreationInformation listCreator = new ListCreationInformation();
listCreator.Title = "CompanyCalendar";
listCreator.Description = "Workcalendar";
listCreator.TemplateType = (int)ListTemplateType.Events;
var ifListExcists = web.Lists.GetByTitle(listCreator.Title);
if (ifListExcists == null)
{
web.Lists.Add(listCreator);
clientContext.ExecuteQuery();
testLabel.Text = "The " + listCreator.Title + " list was created";
}
else
{
testLabel.Text = "List already excist";
}
}
}
protected void myButton_Click(object sender, EventArgs e)
{
Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
{
Web web = clientContext.Web;
var deleteList = web.Lists.GetByTitle("CompanyCalendar");
deleteList.DeleteObject();
clientContext.ExecuteQuery();
testLabel.Text = "list deleted";
}
}
}
}
When I look at my server1 site the list is not there but in the code it seems like its there since my variable "ifListExcists" is never null.
Your ifListExists variable would never be null because its not executed on server.
Use following method to check if list exists or not:
private bool ValdiateList(ClientContext clientContext, string listName, out List existingList)
{
Web web = clientContext.Web;
existingList =null;
ListCollection lists = web.Lists;
var existingLists
= clientContext.LoadQuery(lists.Where(list => list.Title == listName));
clientContext.ExecuteQuery();
existingList = existingLists.FirstOrDefault();
return (existingList != null);
}

Selected Item getting lost on post back (Sharepoint wss3.0 webpart)

I am new Sharepoint developer and trying to create search webpart in window Sharepoint service 3.0 [Free edition], so far I can select multiple item from list box but when i trying to display selected item into textbox it getting lost.
Below is my code:
using System;
using System.Runtime.InteropServices;
using System.Data;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Xml.Serialization;
using System.Collections;
namespace Filter_WebPart
{
[Guid("6641a7a3-d2c4-4fda-9ef5-89596845bd6e")]
public class Filter_WebPart : System.Web.UI.WebControls.WebParts.WebPart
{
protected DataSet _dataset;
protected ListBox lstRegion;
protected ListBox lstMaterial;
protected HtmlButton btnSubmit;
protected HtmlInputText txtDisplay;
private string myExceptions = "";
//private int[] Index1;
protected override void CreateChildControls()
{
try
{
//Region Table / DataSet
lstRegion = new ListBox();
lstRegion.ID="lstRegion";
lstRegion.SelectionMode = ListSelectionMode.Multiple;
//lstRegion.EnableViewState = true;
//lstRegion.SelectedIndex = 0;
//Material Table / DataSet
lstMaterial = new ListBox();
lstMaterial.SelectionMode = ListSelectionMode.Multiple;
lstMaterial.EnableViewState = true;
btnSubmit = new HtmlButton();
btnSubmit.InnerText = "Filter";
btnSubmit.ServerClick += new EventHandler(btnSubmit_Click);
txtDisplay = new HtmlInputText();
//CommandButton
this.Controls.Add(lstRegion);
this.Controls.Add(lstMaterial);
this.Controls.Add(btnSubmit);
this.Controls.Add(txtDisplay);
}
catch(Exception ChildControlException)
{
myExceptions += "ChildControlException:" + ChildControlException.Message;
}
finally
{
//base.CreateChildControls();
}
}
protected override void OnPreRender(EventArgs e)
{
if(!this.Page.IsPostBack)
{
lstMaterial.DataSource = GetMaterialList();
lstMaterial.DataTextField = "Material Name";
lstMaterial.DataValueField = "Material Name";
lstMaterial.DataBind();
lstRegion.DataSource = GetRegionList();
lstRegion.DataTextField = "Region Name";
lstRegion.DataValueField = "Region Name";
lstRegion.DataBind();
txtDisplay.Value="1 time";
}
base.OnPreRender(e);
}
void btnSubmit_Click(object sender, EventArgs e)
{
string tmpStr="";
int k=0;
//int i=0;
lstMaterial.DataBind();
lstRegion.DataBind();
//int[] indx = lstRegion.GetSelectedIndices();
//for(i=0;i<indx.Length;i++)
//{
// tmpStr = tmpStr+","+lstRegion.Items[indx[i]].Text;
//}
//if(lstRegion.SelectedIndex >=0 )
//{
//for(i=0;i < lstRegion.Items.Count;i++)
//{
// //if(i==5 || i==10)
// //{
// // lstRegion.Items[i].Selected = true;
// //}
// if(lstRegion.Items[i].Selected)
// {
// tmpStr = lstRegion.Items[i].Text;
// }
// k=k+1;
//}
//}
foreach(ListItem RgItem in lstRegion.Items)
{
if(RgItem.Selected == true)
{
tmpStr = tmpStr +","+RgItem.Text;
k=k+1;
}
}
//for(i=0;i<lstRegion.Items.Count;i++)
//{
// if(lstRegion.Items[i].Selected == true)
// {
// txtDisplay.Value = txtDisplay.Value +","+lstRegion.Items[i].Text;
// k=k+1;
// }
//}
if(tmpStr != "" )
{txtDisplay.Value = tmpStr;}
else{
txtDisplay.Value = k.ToString();
btnSubmit.InnerText = "Done";}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
private DataSet GetRegionList()
{
_dataset = new DataSet();
DataTable _tbl = new DataTable();
DataColumn _tblcol = new DataColumn("Region Name");
_tbl.Columns.Add(_tblcol);
SPWeb web = SPContext.Current.Site.RootWeb;
SPList myList = web.Lists["Service Area"];
SPQuery query = new SPQuery();
query.Query = "";
SPListItemCollection items = myList.GetItems(query);
foreach (SPListItem item in items)
{
DataRow _row = _tbl.NewRow();
_row[0] = SPEncode.HtmlEncode(item["Region Name"].ToString());
_tbl.Rows.Add(_row);
}
_dataset.Tables.Add(_tbl);
return _dataset;
}
private DataSet GetMaterialList()
{
_dataset = new DataSet();
DataTable _tbl = new DataTable();
DataColumn _tblcol = new DataColumn("Material Name");
_tbl.Columns.Add(_tblcol);
SPWeb web = SPContext.Current.Site.RootWeb;
SPList myList = web.Lists["Material Master"];
SPQuery query = new SPQuery();
query.Query = "";
SPListItemCollection items = myList.GetItems(query);
foreach (SPListItem item in items)
{
DataRow _row = _tbl.NewRow();
_row[0] = SPEncode.HtmlEncode(item["Material Name"].ToString());
_tbl.Rows.Add(_row);
}
_dataset.Tables.Add(_tbl);
return _dataset;
}
protected override void RenderContents(HtmlTextWriter output)
{
try
{
this.EnsureChildControls();
lstRegion.RenderControl(output);
lstMaterial.RenderControl(output);
btnSubmit.RenderControl(output);
output.Write("<br>");
txtDisplay.RenderControl(output);
//base.RenderContents(output);
}
catch (Exception RenderContentsException)
{
myExceptions += "RenderException:" + RenderContentsException.Message;
}
finally
{
if (myExceptions.Length > 0)
{
output.WriteLine(myExceptions);
}
}
}
}
}
This should be working. I've tried your code on my 2010 farm and it works fine (should also work for WSS3).
Did you forget to do an iisreset after updating the assembly ?
Your best chance to finding a solution is to use the debugger. You can attach the debugger to the right w3wp.exe process. If you don't know which one, select them all. Then set a breakpoint on your event handler and check where you lose your selection.
You don't need to override OnInit, you can put EnsureChildControls() in btnSubmit_Click.

Adding description to WebPartPage when creating the page

I am following this (http://msdn.microsoft.com/en-us/library/ms450826.aspx) method to add a webpartpage (samplewpp.aspx) and it works. However, I need to add one line description as well. How?
You need to add a Content Editor Web Part (CEWP) to the page and then add your description to this. The CEWP allows you to put text/html onto a page.
To do this programatically then follow something like this code by Razi bin Rais :-
AddAndFillCEWP("http://server","/" ,"/Pages/blank.aspx","this text is adding via code","Header","CEWP WebPart");
private void AddAndFillCEWP(string siteUrl, string webName, string pageUrl, string textCEWP, string zoneId, string title)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSiteTest = new SPSite(siteUrl))
{
using (SPWeb web = spSiteTest.OpenWeb(webName))
{
try
{
web.AllowUnsafeUpdates = true;
SPFile file = web.GetFile(pageUrl);
if (null != file)
{
using (SPLimitedWebPartManager mgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
if (null != mgr)
{
//create new webpart object
ContentEditorWebPart contentEditor = new ContentEditorWebPart();
//set properties of new webpart object
contentEditor.ZoneID = zoneId;
contentEditor.Title = title;
contentEditor.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
contentEditor.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.TitleAndBorder;
//Add content to CEWP
XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlElement = xmlDoc.CreateElement("Root");
xmlElement.InnerText = textCEWP;
contentEditor.Content = xmlElement;
contentEditor.Content.InnerText = xmlElement.InnerText;
//Add it to the zone
mgr.AddWebPart(contentEditor, contentEditor.ZoneID, 0);
web.Update();
}
}
}
}
finally
{
web.AllowUnsafeUpdates = false;
}
}
}
});
}

Resources