How do you retrieve the URL for a discussion board item? That is, the URL displayed when you mouse over the subject line (once the list has been added to the page as a web part).
protected global::System.Web.UI.WebControls.GridView gvForum;
public string Region
{
get
{
return "";
}
}
public string DefaultRegion { get; set; }
public int Top { get; set; }
public string ListName
{
get
{
string listName=string.Empty;
if (!string.IsNullOrEmpty(this.Region))
listName=string.Format("{0} {1}","Forum",this.Region);
else
listName = string.Format("{0} {1}", "Forum", this.DefaultRegion);
return listName;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
string region = this.Region;
string caml=#"<OrderBy><FieldRef Name=""Modified"" /></OrderBy>";
try
{
using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPQuery spQ = new SPQuery();
spQ.Query = caml;
spQ.RowLimit = (uint)this.Top;
SPList spList = spWeb.Lists[ListName];
SPListItemCollection items = spList.GetItems(spQ);
if (items != null && items.Count > 0)
{
gvForum.DataSource = items;
gvForum.DataBind();
}
else
{
this.Visible = false;
}
}
}
}
catch (Exception ex)
{
Logger.Log(ex.Message, System.Diagnostics.EventLogEntryType.Error);
}
}
protected void gvForum_RowDataBound(object sender, GridViewRowEventArgs e)
{
SPListItem item = e.Row.DataItem as SPListItem;
Label lblTitle = e.Row.FindControl("lblTitle") as Label;
HtmlAnchor aURL = e.Row.FindControl("aURL") as HtmlAnchor;
if (item != null)
{
if (lblTitle != null && aURL != null)
{
aURL.HRef = "~/" + item.Url;
lblTitle.Text = item["Title"].ToString();
}
}
}
protected void gvForum_RowDataBound(object sender, GridViewRowEventArgs e)
{
SPListItem item = e.Row.DataItem as SPListItem;
Label lblTitle = e.Row.FindControl("lblTitle") as Label;
HtmlAnchor aURL = e.Row.FindControl("aURL") as HtmlAnchor;
if (item != null)
{
if (lblTitle != null && aURL != null)
{
aURL.HRef = "~/" + item.Url;
lblTitle.Text = item["Title"].ToString();
}
}
}
You can use use "TopicPageUrl" field column to directly get the discussion topic by using REST api URL
http://sp2013.in/_api/web/Lists/GetByTitle('Discussion')/Items?$select=Title,TopicPageUrl,DiscussionLastUpdated,Folder/ItemCount,LastReplyBy/Title,Author/Title&$expand=Folder,LastReplyBy,Author&$orderby=DiscussionLastUpdated desc
The above code is also useful to get discussion last updated, reply count (its saved in folder), last replied by.
Are you asking how to find the URL for an individual discussion in a discussion board? Or an individual reply to a discussion?
You can give just subject name like http://site/discussion/lists/discussionboard/discusontitlename or subject
You may not have the list item, but if you do just look at the "FileRef" property. It will look like "https://mycompany.sharepoint.com/sites/Lists/discussion/". If I put that URL in the browser (I'm using SharePoint Online), it redirects me to the https://mycompany.sharepoint.com/Lists/Discussion/Flat.aspx?RootFolder=... URL.
To generate the direct url to a particular discussion item, on Client side (using a REST API call), you could try this:
var jqXhr = $.ajax({
url:"/DiscussionSite/_api/lists/getByTitle('Discussions')/items?
$select=ID,FileRef,ContentTypeId,Title,Body&
$filter=ContentType eq 'Discussion'",
headers: { 'Accept': 'application/json;odata=verbose'}
});
// Fetch only the discussions from the Discussion list (excl. Messages)
jqXhr.done(function(data){
// Picking only the first item for testing purpose
// Feel free to loop through the response if necessary
var firstItem = data.d.results[0],
firstItemUrl = '/DiscussionSite/Lists/Discussions/Flat.aspx?RootFolder=' + firstItem.FileRef + '&FolderCTID' + firstItem.ContentTypeId;
// Result - /DiscussionSite/Lists/Discussions/Flat.aspx?RootFolder=/DiscussionSite/Lists/Discussions/My Discussion Topic 1&FolderCTID0x01200200583C2BEAE375884G859D2C5A3D2A8C06
// You can append "&IsDlg=1" to the Url for a popup friendly display of the Discussion Thread in a SharePoint Modal Dialog
console.log(firstItemUrl);
});
Hope this helps!
Related
Anyone know if it's possible to combine a field like Item Class (we use a 3 letter code for each one) with a sequential number to get a unique Inventory ID?
e.g. we need all hardware to be HWR-00988 but all Shipping Supplies to be SUP-00989 and so on.
My workaround right now is to create an Attribute called ITEMCLASS and basically mirror the item class codes (HWR, SUP, etc) then add attributes to each Item Class and use the Inventory ID Segment Settings to make it look like it's pulling the actual Item Class.
Seems like this should exist though? I know the data exists in INITEMMENU already.
If you mean having a unique InventoryCD key that switches between constants HWR-XXXXX and SUP-XXXXX based on custom business rules (like appending Item Class); I don't think that's possible out-of-box without programming.
Usually this is accomplished with a custom attribute. Here's an example for [CuryID] attribute which computes key value based on arbitrary logic.
Usage, decorate key fields with custom attribute [CuryID]:
[PXDBString(5, IsUnicode = true)]
[PXDefault(typeof(AccessInfo.baseCuryID))]
[PXUIField(DisplayName = "Currency", ErrorHandling = PXErrorHandling.Never)]
[PXSelector(typeof(Currency.curyID))]
[CuryID]
public virtual String CuryID { get; set; }
For your scenario you would replace InventoryRaw with your custom attribute:
[PXDefault]
[InventoryRaw(IsKey = true, DisplayName = "Inventory ID")]
public virtual String InventoryCD { get; set; }
Custom attribute [CuryID], if key is autogenerated consider adding FieldDefaulting event:
public sealed class CuryIDAttribute : PXEventSubscriberAttribute, IPXFieldUpdatedSubscriber, IPXRowSelectedSubscriber, IPXRowUpdatingSubscriber, IPXRowUpdatedSubscriber, IPXFieldVerifyingSubscriber
{
public void FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
{
CurrencyInfo info = e.Row as CurrencyInfo;
if (info != null)
{
//reset effective date to document date first
info.SetDefaultEffDate(sender);
try
{
info.defaultCuryRate(sender);
}
catch (PXSetPropertyException ex)
{
sender.RaiseExceptionHandling(_FieldName, e.Row, sender.GetValue(e.Row, _FieldOrdinal), ex);
}
info.CuryPrecision = null;
}
}
public void RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
CurrencyInfo info = e.Row as CurrencyInfo;
if (info != null)
{
bool disabled = info.IsReadOnly == true || (info.CuryID == info.BaseCuryID);
PXUIFieldAttribute.SetEnabled<CurrencyInfo.curyMultDiv>(sender, info, !disabled);
PXUIFieldAttribute.SetEnabled<CurrencyInfo.sampleCuryRate>(sender, info, !disabled);
PXUIFieldAttribute.SetEnabled<CurrencyInfo.sampleRecipRate>(sender, info, !disabled);
PXUIFieldAttribute.SetEnabled<CurrencyInfo.curyRateTypeID>(sender, info, !disabled);
PXUIFieldAttribute.SetEnabled<CurrencyInfo.curyEffDate>(sender, info, !disabled);
PXUIFieldAttribute.SetEnabled<CurrencyInfo.baseCuryID>(sender, info, false);
PXUIFieldAttribute.SetEnabled<CurrencyInfo.displayCuryID>(sender, info, false);
PXUIFieldAttribute.SetEnabled<CurrencyInfo.curyID>(sender, info, true);
}
}
private bool? currencyInfoDirty = null;
public void RowUpdating(PXCache sender, PXRowUpdatingEventArgs e)
{
CurrencyInfo info = e.Row as CurrencyInfo;
if (info != null && info._IsReadOnly == true)
{
e.Cancel = true;
}
else
{
currencyInfoDirty = sender.IsDirty;
}
}
public void RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
{
CurrencyInfo info = e.Row as CurrencyInfo;
if (info != null)
{
CurrencyInfo old = e.OldRow as CurrencyInfo;
if (old != null && (String.IsNullOrEmpty(info.CuryID) || String.IsNullOrEmpty(info.BaseCuryID)))
{
info.BaseCuryID = old.BaseCuryID;
info.CuryID = old.CuryID;
}
if (currencyInfoDirty == false
&& info.CuryID == old.CuryID
&& info.CuryRateTypeID == old.CuryRateTypeID
&& info.CuryEffDate == old.CuryEffDate
&& info.CuryMultDiv == old.CuryMultDiv
&& info.CuryRate == old.CuryRate)
{
sender.IsDirty = false;
currencyInfoDirty = null;
}
}
}
public void FieldVerifying(PXCache sender, PXFieldVerifyingEventArgs e)
{
CurrencyInfo info = e.Row as CurrencyInfo;
if (info != null)
{
CMSetup CMSetup = info.getCMSetup(sender);
}
}
}
It's probably pretty obvious, but I'm completely new to programming or asking a question at stackoverflow, so I apologize in advance if I can't explain myself properly. Also, there are some parts I have no idea what they are for anymore since the code is basically a mix of tutorials.
What I need the app to do is for it to keep doing what it's doing (the handler part), but while it's is closed (not minimized). But instead of changing the background, I need it to send a notification instead.
In other words, every 10 minutes, if the value of temperBU is 19, I get a notification even if the app is closed.
For that, if I'm not mistaken, what I need is a service, but I don't understand what type is better for this situation. I tried some tutorials, but nothing seems to work, and if it's possible to start the service as soon as the app gets started.
public class MainActivity extends AppCompatActivity {
ConstraintLayout layout;
class Weather extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... address) {
try {
URL url = new URL(address[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
String content = "";
char ch;
while (data != -1) {
ch = (char) data;
content = content + ch;
data = isr.read();
}
Log.i("Content", content);
return content;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String content;
Weather weather = new Weather();
{
{
try {
content = weather.execute("https://api.openweathermap.org/data/2.5/weather?q=budapest,hu&units=metric&appid=ce2fd10cdcc8ab209f979f6a41c27cfe").get();
JSONObject jsonObject = new JSONObject(content);
String mainData = jsonObject.getString("main");
Log.i("mainData", mainData);
JSONObject object = new JSONObject(mainData);
Double temp = object.getDouble("temp");
Log.i("temp", String.valueOf(temp));
int temperBU = (int) Math.round(temp);
Log.i("temperBU", String.valueOf(temperBU));
layout = findViewById(R.id.hs_n);
if (temperBU == 19)
layout.setBackgroundResource(R.drawable.hungry_summer_premium_yes_simple);
else layout.setBackgroundResource(R.drawable.hungry_summer_premium_no_simple);
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
String content;
Weather weather = new Weather();
try {
content = weather.execute("https://api.openweathermap.org/data/2.5/weather?q=budapest,hu&units=metric&appid=ce2fd10cdcc8ab209f979f6a41c27cfe").get();
JSONObject jsonObject = new JSONObject(content);
String mainData = jsonObject.getString("main");
Log.i("mainData", mainData);//*
JSONObject object = new JSONObject(mainData);
Double temp = object.getDouble("temp");
Log.i("temp", String.valueOf(temp));
int temperBU = (int) Math.round(temp);
Log.i("temperBU", String.valueOf(temperBU));//*
layout = findViewById(R.id.hs_n);
if (temperBU == 19)
layout.setBackgroundResource(R.drawable.hungry_summer_premium_yes_simple);
else
layout.setBackgroundResource(R.drawable.hungry_summer_premium_no_simple);
} catch (Exception e) {
e.printStackTrace();
}
handler.postDelayed(this::run, 600000);
}
};
handler.postDelayed(r, 600000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Thank you so much for the help.
Please note that AsyncTask is deprecated, so use the following to do a background work:
Android AsyncTask API deprecating in Android 11.What are the alternatives?
In order to continue doing something after the user closed your app try using foreground service, like this:
in Android manifest, add
uses-permission android:name="android.permission.FOREGROUND_SERVICE"
this inside the application tag:
service android:name=".services.WorkerSvc"
add this class:
class WorkerSvc : Service() {
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
LogUtil.i("onStartCommand")
startForeground(
NotificationUtil.NOTIFICATION_ID,
NotificationUtil.makeForeGroundNotification(getString(R.string.please_wait))
)
processIntent(intent)
return START_STICKY
}
private fun processIntent(intent: Intent?) {
if (intent == null) {
stopSelf()
} else {
// DO YOUR WORK HERE. USE INTENT EXTRAS TO PASS DATA TO SERVICE
// NOTE THIS IS EXECUTED IN MAIN THREAD SO USE ONE OF THE SOLUTION PROVIDED IN A LINK ABOVE
}
}
}
To start the service:
val svcIntent = Intent(App.instance, WorkerSvc::class.java)
svcIntent.putExtra(
//DATA TO PASS TO SERVICE
)
if (context != null) {
ContextCompat.startForegroundService(context, svcIntent)
}
I am new to jsf and I am setting up a basic reporting tool (sql queries) which shows a list of reports in the home page. I want to put an excel export commandbutton in the home page and export the report selected by the user or drive the user to a different execution page to show results in a datatable for the selected report. How can I achieve that? datatable with query results, of course, is visible only in the execution page and is dynamically created during query execution (this part works fine). Am I going crazy for nothing? Thanks in advance for any suggestion.
If you want to export data to Excel you need to use a third party library. There are free ones like JExcelApi and Apache POI. Also, there are commercial libraries like Aspose. If you're going to choose an open source library check this question: Choosing an excel java api.
When you export data to Excel, you must create the Excel file and download the content for the client. You can check how to download a file using JSF by #BalusC (JSF expert).
One more advice, when you're downloading a file don't add ajax functionality to the command link/button.
You can use under code this code block provide excel export as genericly way. You can send any List and send any fileName
public class ExcelUtils {
public static <T> void writeToExcel(String fileName, List<T> data) {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
response.setHeader("Pragma", "no-cache");
OutputStream fos = null;
try {
fos = response.getOutputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
XSSFWorkbook workbook = null;
try {
// File file = new File(fileName);
workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
List<String> fieldNames = getFieldNamesForClass(data.get(0).getClass());
int rowCount = 0;
int columnCount = 0;
Row row = sheet.createRow(rowCount++);
for (String fieldName : fieldNames) {
if (!fieldName.equals("serialVersionUID")) {
Cell cell = row.createCell(columnCount++);
cell.setCellValue(fieldName);
}
}
Class<? extends Object> classz = data.get(0).getClass();
for (T t : data) {
row = sheet.createRow(rowCount++);
columnCount = 0;
for (String fieldName : fieldNames) {
if (!fieldName.equals("serialVersionUID")) {
Cell cell = row.createCell(columnCount);
Method method = null;
try {
method = classz.getMethod("get" + capitalize(fieldName));
} catch (NoSuchMethodException nme) {
method = classz.getMethod("get" + fieldName);
}
Object value = method.invoke(t, (Object[]) null);
if (value != null) {
if (value instanceof String) {
cell.setCellValue((String) value);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
} else if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
}
}
columnCount++;
}
}
}
workbook.write(fos);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
context.responseComplete();
context.renderResponse();
}
} catch (IOException e) {
}
try {
if (workbook != null) {
workbook.close();
}
} catch (IOException e) {
}
}
}
// retrieve field names from a POJO class
private static List<String> getFieldNamesForClass(Class<?> clazz) throws Exception {
List<String> fieldNames = new ArrayList<String>();
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fieldNames.add(fields[i].getName());
}
return fieldNames;
}
// capitalize the first letter of the field name for retriving value of the
// field later
private static String capitalize(String s) {
if (s.length() == 0)
return s;
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
I am in the process of upgrading our custom solutions to Sharepoint 2010. I wanted to utilize the WorkflowCompleted event handler but I don't seem to be able to get the relevant SPListItem from the event properties.
I tried using SPWorkflowEventProperties.ActivationProperties but this always returns null (even in the WorkflowStarted event handler).
How do I get the context from workflow event handlers (SPListItem, SPWeb, SPSite etc)?
I've found the same thing. SPWorkflowEventProperties is practically useless since just about everything is null. It doesn't tell status (Approved, Rejected, etc). And, most importantly, it doesn't (directly) tell what item was completed. Hopefully this will be addressed in future versions. In the meantime, I used the following:
public override void WorkflowCompleted(SPWorkflowEventProperties properties)
{
using (SPSite site = new SPSite(properties.WebUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPListItem task = GetApprovedTask(properties, web);
SPListItem item = GetApprovedItem(web, task);
if (null != item)
{
// TODO : process approved item
}
}
}
}
private SPListItem GetApprovedItem(SPWeb web, SPListItem task)
{
SPListItem item = null;
if (null != task)
{
SPList list = web.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
item = list.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
}
return item;
}
private SPListItem GetApprovedTask(SPWorkflowEventProperties properties, SPWeb web)
{
SPListItem item = null;
string caml = #"<Where><And><And><And><Eq><FieldRef Name='WorkflowOutcome' /><Value Type='Text'>Approved</Value></Eq><Eq><FieldRef Name='WorkflowInstanceID' /><Value Type='Guid'>{0}</Value></Eq></And><IsNotNull><FieldRef Name='WorkflowListId' /></IsNotNull></And><IsNotNull><FieldRef Name='WorkflowItemId' /></IsNotNull></And></Where>";
SPQuery query = new SPQuery();
query.Query = string.Format(caml, properties.InstanceId);
query.RowLimit = 1;
SPList list = web.Lists["Tasks"];
SPListItemCollection items = list.GetItems(query);
if (items.Count > 0)
{
item = items[0];
}
return item;
}
You can use the InstanceId property to retrieve the SPListItem from the workflow task list as shown in this post
http://blog.symprogress.com/2011/09/sp-2010-get-workflow-status-workflowcompleted-event/
If you can be more generous with details I can be more specific with answer.
But this is generally what you need to do:
Set context specific properties
public static DependencyProperty _ContextProperty
= System.Workflow.ComponentModel.DependencyProperty.Register("_Context",
typeof(WorkflowContext), typeof(MyCustomActivity));
[Description("Site Context")]
[Category("User")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public WorkflowContext __Context
{
get
{
return ((WorkflowContext)(base.GetValue(MyCustomActivity.__ContextProperty)));
}
set
{
base.SetValue(MyCustomActivity.__ContextProperty, value);
}
}
public static DependencyProperty __ListIdProperty
= System.Workflow.ComponentModel.DependencyProperty.Register("__ListId",
typeof(string), typeof(MyCustomActivity));
[ValidationOption(ValidationOption.Required)]
public string __ListId
{
get
{
return ((string)(base.GetValue(MyCustomActivity.__ListIdProperty)));
}
set
{
base.SetValue(MyCustomActivity.__ListIdProperty, value);
}
}
public static DependencyProperty __ListItemProperty
= System.Workflow.ComponentModel.DependencyProperty.Register("__ListItem",
typeof(int), typeof(MyCustomActivity));
[ValidationOption(ValidationOption.Required)]
public int __ListItem
{
get
{
return ((int)(base.GetValue(MyCustomActivity.__ListItemProperty)));
}
set
{
base.SetValue(MyCustomActivity.__ListItemProperty, value);
}
}
public static DependencyProperty __ActivationPropertiesProperty
= DependencyProperty.Register("__ActivationProperties",
typeof(Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties), typeof(MyCustomActivity));
[ValidationOption(ValidationOption.Required)]
public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties __ActivationProperties
{
get
{
return (Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties)base.GetValue(MyCustomActivity.__ActivationPropertiesProperty);
}
set
{
base.SetValue(MyCustomActivity.__ActivationPropertiesProperty, value);
}
}
You will get context in __Context and everything else from __Context like this:
protected override ActivityExecutionStatus
Execute(ActivityExecutionContext executionContext) {
// Raise Invoke Event to execute custom code in the workflow.
this.RaiseEvent(MyCustomActivity.InvokeEvent,
this, EventArgs.Empty);
SPWeb _cxtWeb = null;
String _strLinfo = "Dll;";
String _strTo = String.Empty;
// Set Context
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (_cxtWeb = __Context.Web)
{
//_cxtWeb = __Context.Web;
Guid _cListId = new Guid(__ListId);
SPList _cSPList = _cxtWeb.Lists[_cListId]; // TimeLog
SPListItem _cListItem = _cSPList.GetItemById(__ListItem);
SMTPSERVER = _cxtWeb.Site.WebApplication
.OutboundMailServiceInstance.Server.Address;
}
});
}
catch { /**/ }
}
protected void getNews()
{
using (SPWeb web = getWeb("InternalNews"))
{
fetchNewsFromWeb(ref dtNews,true,"English",new string[] { "Internal news page" },web,startDate,endDate,false,true);
}
}
protected SPWeb getWeb(string contentTypeUrlKey)
{
try
{
List<string> urls = CTUrlWrapper.GetContentTypeUrl(contentTypeUrlKey, this.Page.Request.Url.ToString());
return SPContext.Current.Site.OpenWeb(urls[0].ToLowerInvariant().Replace(SPContext.Current.Site.Url.ToLowerInvariant(), "").TrimStart('/'));
}
catch
{
throw new Exception("Can not fetch value from CTUrl list, key: \"" + contentTypeUrlKey + "\"");
}
}
Do I really need to dispose the web in fetchNewsFromWeb method?
protected DataTable fetchNewsFromWeb(ref DataTable dtAllData, bool useCriticalField, string pageLanguage, string[] contentTypes, SPWeb web, DateTime? fromDate, DateTime? toDate, bool otherUnitNews, bool useHeaderPrefix)
{
SPSiteDataQuery sdq = GetQuery(useCriticalField);
StringBuilder sbQuery = new StringBuilder();
sbQuery.Append(getWhereClause(pageLanguage, fromDate, toDate, contentTypes, otherUnitNews));
sbQuery.Append(getOrderByClause(useCriticalField));
sdq.Query = sbQuery.ToString();
try
{
DataTable foundItems = web.GetSiteData(sdq);
if (foundItems.Rows.Count > 0)
{
foreach (DataRow row in foundItems.Rows)
{
try
{
object[] dtAlldataTemp = extractNewsFields(row, useHeaderPrefix);
dtAllData.Rows.Add(dtAlldataTemp);
}
catch (Exception ex)
{
}
}
}
}
catch (Exception ex)
{
}
finally {web.Dispose();}// do we really need this here?
return dtAllData;
}
protected SPWeb getWeb(string contentTypeUrlKey)
{
try
{
List<string> urls = CTUrlWrapper.GetContentTypeUrl(contentTypeUrlKey, this.Page.Request.Url.ToString());
return SPContext.Current.Site.OpenWeb(urls[0].ToLowerInvariant().Replace(SPContext.Current.Site.Url.ToLowerInvariant(), "").TrimStart('/'));
}
catch
{
throw new Exception("Can not fetch value from CTUrl list, key: \"" + contentTypeUrlKey + "\"");
}
}
No you don't.
The using will take care of disposing it already.
Did you ask SPDisposeCheck?
It depends on how getWeb function is returning the SPWeb.
If its just a SPContext.Current.Web - > Answer is No.
If its returned by opening a new web using OpenWeb() call. Answer is Yes.
Can you not pass the web by ref and have the outer dispose take are of it?