Sharepoint Smartpart Issue - sharepoint

I am very new to Sharepoint programming, like the rest of my team is. We have decided to use smart part as our bridge between sharepoint and our development efforts. After some effort we got it up and running. However, the problem is, that when i use a simple user control for test, with sharepoint om code that gets names of files in a document library, sharepoint gives me a rather helpful "An unknown error has occured". This code works just fine when inside an aspx page. I have written another simple test user control that just executes a Response.Write() line to check is there a problem with executing code, but this one works just fine in smart part too.
Code goes like
protected void Button1_Click(object sender, EventArgs e)
{
Microsoft.SharePoint.SPSite srv1 =
new SPSite("http://server:port/");
SPWeb web = srv1.OpenWeb();
var list = web.GetFolder("http://server:port/documentLibrary");
for (int i = 0; i < list.Files.Count; i++)
{
ListBox1.Items.Add(list.Files[i].Name);
}
}
Anything we may be missing or doing wrong?
Many thanks in advance...

AFAIK, Smart Part hasn't been really needed since SharePoint 2003. Why don't you just create a regular user control and plop it in the /ControlTemplates folder? Deploy it is as part of a Feature with related code, if appropriate...
Also, update your Web.Config file to display meaningful error messages:
customErrors=off
Enable Stack Traces by adding CallStack=”true” to the SafeMode tag
Set the compilation debug attribute to "true"

Just a side note, you should generally wrap your SPSite and SPWeb objects in a using clause as these are unmanaged objects as outlined here:
http://msdn.microsoft.com/en-us/library/aa973248.aspx
protected void Button1_Click(object sender, EventArgs e)
{
using (Microsoft.SharePoint.SPSite srv1 = new SPSite("http://server:port/"))
{
using (SPWeb web = srv1.OpenWeb())
{
var list = web.GetFolder("http://server:port/documentLibrary");
for (int i = 0; i < list.Files.Count; i++)
{
ListBox1.Items.Add(list.Files[i].Name);
}
}
}
}

Ok it's solved, thanks everybody for information and help.
It was about trust level and i set thrust level to "WSS_Medium" in relevant site collection's web.config file.
<trust level="WSS_Medium" originUrl="" />
I have found this solution (along with some more relevant information on subject) in Jan Tielen's blog at here

Related

Export to Excel from grid - no data

I am getting an Excel spreadsheet with columns but, no data when I click on the Excel icon on a grid.
I have put a grid on the CR306030 page that is tied to a view of a custom DAC that relates back to the CRActivity record for the page. I have set the SkinID to Inquire and the AllowImport = true. The view in my Graph extension class looks like this:
[PXImport(typeof(CRActivity))]
public PXSelect<MyDac,
Where<MyDac.activityNoteID,
Equal<Current<CRActivity.noteID>>>> MyDacView;
I'm not sure what I am missing. I am trying to export the data in the grid so, I may be way off here.
TIA!
This happened because I had an update() call inside of a FieldSelecting() event handler. This, for some reason, caused the export to quit working. This presents another problem for me that I will post in another question but, the export issue is resolved. Here's what my code looked like in the extended graph that was causing the issue:
protected virtual void CRActivity_UsrCustomField_FieldSelecting(PXCache cache, PXFieldSelectingEventArgs e)
{
CRActivity activity = (CRActivity) e.Row;
CRActivityExt activityExt = activity.GetExtension<CRActivityExt>();
// Some code here.
e.ReturnValue = TotalValue;
activityExt.UsrCustomField = TotalValue;
Base.Events.Update(activity);
}
I changed it to this in order to get the export working:
protected virtual void CRActivity_UsrCustomField_FieldSelecting(PXCache cache, PXFieldSelectingEventArgs e)
{
CRActivity activity = (CRActivity) e.Row;
CRActivityExt activityExt = activity.GetExtension<CRActivityExt>();
// Some code here.
e.ReturnValue = TotalValue;
//activityExt.UsrCustomField = TotalValue;
//Base.Events.Update(activity);
}
Adding Export button is all that should be required. Setting SkinID to inquire will do that for you.
It seems you are running into an uncommon scenario so I would suggest to rollback tentative solutions like adding Import functionality that isn't required in case your implementation has errors causing conflicts with export functionality.
Next issue I would suspect is a kind of security/rights issues or an explicit call to disallow exporting records. Removing unnecessary code and substituting the DAC you are using could help expose the root cause as some specific entity could have been locked down by security while others aren't.
If you're familiar with Acumatica web services it could be worth a shot to test if records from the grid can be retrieved by web service. If they can't then that points towards security/rights issues.

Change XSLT of the SearchResultWebPart during the FeatureActivated

I have a piece of code which changes XSLT of a SearchResultWebPart at Sharepoint 2010 Search Center result page (spFileItem - is SPFile of a search result page) :
SPLimitedWebPartManager wpManager = spFileItem.GetLimitedWebPartManager(PersonalizationScope.Shared);
foreach (WebPart wpItem in wpManager.WebParts)
{
if (wpItem is CoreResultsWebPart)
{
((CoreResultsWebPart)wpItem).UseLocationVisualization = false;
((CoreResultsWebPart)wpItem).Xsl = someXSL;
wpManager.SaveChanges(wpItem);
}
spFileItem.Update();
spFileItem.CheckIn(Consts.CheckInComment, SPCheckinType.MajorCheckIn);
But, this code doesn't work if it is called on feature activated (gives InvalidOperationException - incorrect object state). However it perfectly works in Console application.
After some reflecting, I found out that there is a piece of code inside the SearchResultWebPart, which checks if the webpart wasn't initialized - it throws the mentioned above exception on setting XSL property. Does anybody know how to work this problem out? For me it'd be quite convenient to do XSL change at FeatureActivated...
I found a solution to my problem, but it uses different way of setting xsl for SearchResultBaseWebPart.
SPLimitedWebPartManager wpManager = spFileItem.GetLimitedWebPartManager(PersonalizationScope.Shared);
foreach (WebPart wpItem in wpManager.WebParts)
{
if (wpItem is CoreResultsWebPart)
{
((CoreResultsWebPart)wpItem).UseLocationVisualization = false;
((CoreResultsWebPart)wpItem).XslLink = spFileItem.Web.Url + #"/_layouts/XSL/MYXSL.xsl";
wpManager.SaveChanges(wpItem);
}
}
spFileItem.Update();
spFileItem.CheckIn(Consts.CheckInComment, SPCheckinType.MajorCheckIn);
I feel you mix up a few things in the question. You would like to set the Xsl property of the CoreResultsWebPart. This class has no direct implementation of the Xsl method, so it inherits the implementation of its parent class (SearchResultBaseWebPart). The Xsl property setter try to set the XslHash property (but only if we are after the OnInit that sets _BeforeOnInit = false;), and the setter method of the XslHash property throws an InvalidOperationException, but this exception should be catched by the try/catch block in Xsl property setter anyway. I don't see any other potential source of InvalidOperationException in the code.
You should check the patch level of your SP2010 (is it SP1/some of the cummulative updates/original version?) and try to activate the feature from different contexts (from web site / STSADM or PowerShell).
But first I suggest you to add a try / catch block to your feature receiver code and trace out the error details (like stack trace) and monitor the results using DebugView.

Using log4net as a logging mechanism for SSIS?

Does anyone know if it is possible to do logging in SSIS (SQL Server Integration Services) via log4net? If so, any pointers and pitfalls to be aware of? How's the deployment story?
I know the best solution to my problem is to not use SSIS. The reality is that as much as I hate this POS technology, the company I work with encourages the use of these apps instead of writing code. Meh.
So to answer my own question: it is possible. I'm not sure how our deployment story will be since this will be done in a few weeks from now.
I pretty much took the information from these sources and made it work. This one explains how to make referencing assemblies work with SSIS, click here. TLDR version: place it in the GAC and also copy the dll to the folder of your targetted framework. In my case, C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727. To programmatically configure log4net I ended up using this link as reference.
This is how my logger configuration code looks like for creating a file with the timestamp on it:
using log4net;
using log4net.Config;
using log4net.Layout;
using log4net.Appender;
public class whatever
{
private ILog logger;
public void InitLogger()
{
PatternLayout layout = new PatternLayout("%date [%level] - %message%newline");
FileAppender fileAppenderTrace = new FileAppender();
fileAppenderTrace.Layout = layout;
fileAppenderTrace.AppendToFile = false;
// Insert current date and time to file name
String dateTimeStr = DateTime.Now.ToString("yyyyddMM_hhmm");
fileAppenderTrace.File = string.Format("c:\\{0}{1}", dateTimeStr.Trim() ,".log");
// Configure filter to accept log messages of any level.
log4net.Filter.LevelMatchFilter traceFilter = new log4net.Filter.LevelMatchFilter();
traceFilter.LevelToMatch = log4net.Core.Level.All;
fileAppenderTrace.ClearFilters();
fileAppenderTrace.AddFilter(traceFilter);
fileAppenderTrace.ImmediateFlush = true;
fileAppenderTrace.ActivateOptions();
// Attach appender into hierarchy
log4net.Repository.Hierarchy.Logger root = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root;
root.AddAppender(fileAppenderTrace);
root.Repository.Configured = true;
logger = log4net.LogManager.GetLogger("root");
}
}
Hopefully this might help someone in the future or at least serve as a reference if I ever need to do this again.
Sorry, you didn't dig deep enough. There are 5 different destinations that you can log to, and 7 columns you can choose to include or not include in your logging as well as between 18 to 50 different events that you can capture logging on. You appear to have chosen the default logging, and dismissed it because it didn't work for you out of the box.
Check these two blogs for more information on what can be done with SSIS logging:
http://consultingblogs.emc.com/jamiethomson/archive/2005/06/11/SSIS_3A00_-Custom-Logging-Using-Event-Handlers.aspx
http://www.sqlservercentral.com/blogs/michael_coles/archive/2007/10/09/3012.aspx

trust set to Full, but web part still causes SecurityException

I've got a web part that accesses the SP object model, packaged in an assembly which is signed and deployed to the GAC. The web.config is set for "Full" trust, and yet my web part throws a SecurityException. The offending lines of code:
SPSecurity.RunWithElevatedPrivileges(new SPSecurity.CodeToRunElevated(() =>
{
foreach (SPGroup g in user.Groups)
{
identity += String.Format(",'{0}'", g.Name.ToLowerInvariant().Replace(#"\", #"\\"));
}
}));
It appears that the exception is thrown when RunWithElevatedPrivileges is called (in other words, my delegate doesn't execute at all). Any ideas? I'm completely bewildered at this point.
update: here's what the code looked like before I wrapped it in the RunWithElevatedPrivileges method:
public MyWebPart()
{
context = new MyProject.Data.MyDataContext(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString);
SPUser user = SPContext.Current.Web.CurrentUser;
identity = String.Format("'{0}'", user.LoginName.ToLowerInvariant().Replace(#"\", #"\\"));
foreach (SPGroup g in user.Groups)
{
identity += String.Format(",'{0}'", g.Name.ToLowerInvariant().Replace(#"\", #"\\"));
}
identity = '[' + identity + ']';
}
And the exception:
System.Security.SecurityException occurred
Message="Request failed."
Source="Microsoft.SharePoint"
StackTrace:
at Microsoft.SharePoint.SPBaseCollection.System.Collections.IEnumerable.GetEnumerator()
at MyProject.MyWebPart..ctor()
InnerException:
Based on the highlight provided by the exception helper, it looks like the attempted access of the SPUser.Groups property is the problem: user.Groups.
What's got me really confused is that this exact code was working fine two days ago, but I had some other problems with the farm and basically had to rebuild it. After getting everything else back up again, I went and tried to add this web part to a page and this problem manifested itself. I tried wrapping the code in the RunWithElevatedPrivileges wrapper to see if I could isolate exactly the offending bit, but it looks like anything that touches the SP oject model causes the exception, including the RunWithElevatedPrivileges method.
update2: I still don't know the real reason this was failing, but it was happening when I was trying to add the web part. After setting breakpoints in the debugger, I realized that the constructor was being called twice; the first time, it all worked exactly as expected, but the second time was when the exception was being thrown. I still have no idea why. I found two ways around this: move the offending code out of the constructor into a later point in the lifecycle of the web part, or comment out the code to add the web part, then uncomment it and redeploy.
Apparently, the reason this "worked 3 days ago" was because I had added my web part to a page a long time ago, and then added the above code to the constructor. Since the web part was already added, I never saw any problems. Later, when I recently had to rebuild the site and add the web part to the page again, this problem manifested itself. So technically, it didn't "work" before, I just wasn't doing the thing that made it misbehave.
Anyway, like I said - I still don't know the true cause of the exception, so answers along those lines are still welcome.
The problem could occur if you try to work with SharePoint objects which were created outside of the RunWithElevatedPrivileges() method, and therefore still hold their old security context. In your case you use a SPUser object which was not created within the RunWithElevatedPrivileges() method.
To work around, you should create the object you want to work with within the delegate. Safe Ids or URLs outside of the delegate, to use them for recreating the objects. E.g.: safe the URL or ID of a SPSite object and use it to create it again within the delegate.
public void Demo()
{
string siteURL = SPContext.Current.Site.Url;
SPSecurity.RunWithElevatedPrivileges(delegate(){
using (SPSite safeSite = new SPSite(siteURL))
{
// place your code here ...
}
});
}
Perhaps you could post the stack trace so we can get some more information.

Sharepoint: How to find out whether an realtive URL is available or already used by a site

How could I find out if a URL is available and usable to create a new site within a site collection or whether it is already in use by an other site, list or library?
Assumed that the relative URL "/newUrl/ is not yet in use, the following code won't actually throw an exception until you try to access any of the SPWeb's properties.
using(SPSite site = new Site("http://portal/"))
{
SPWeb web = site.OpenWeb("/newUrl/"); // no exception
string title = web.Title; // throws exception
}
Of course it would be possible to check the availableness of the URL this way, but it would be more like a hack than like good code.
So got anyone any ideas how to solve this?
Bye,
Flo
The normal answer is
if(web.Exists)
But... you might want to wrap this SPWeb into a using.
using(SPWeb web = site.OpenWeb("/newUrl/"))
{
if(web.Exists)
{
string title = web.Title;
}
}
if (web.Exists)
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.exists.aspx

Resources