I am writing code to check if an item exist in a sharepoint document library, I have generated entity classes using sp metal. The code is below:
public bool? checkRSA(string pin)
{
bool ?checkIfRsaExists = null;
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
string siteURL = "http://dms.site.com/sites/DirOperations/CustomerCare";
CustomercareDataContext CustCareDB = new CustomercareDataContext(siteURL);
checkIfRsaExists = CustCareDB.GetList<BenefitsCT>("RSAs Library").ScopeToFolder("", true).Any(x => x.RSAPIN == pin);
});
return checkIfRsaExists;
}
Now each time I run this code it throws an error: Specified cast is not valid.
The stack trace is below:
StackTrace at Set__permi(Object , Object )\r\n at
Microsoft.SharePoint.Linq.SPItemMappingInfo.MaterializeEntity[TEntity](DataContext
dc, SPDataList list, SPListItem item, SPItemMappingInfo
itemMappingInfo, JoinPath joinPath)\r\n at lambda_method(Closure ,
SPListItem )\r\n at
System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n
at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func`2
predicate)\r\n at
Microsoft.SharePoint.Linq.SPLinqProvider.Execute[T](Expression
expression)\r\n at
linkApprovals.WebService1.<>c__DisplayClass2_0.b__0() in
c:\users\sp_admin\documents\visual studio
2015\Projects\linkApprovals\linkApprovals\WebService1.asmx.cs:line
75\r\n at
Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated
secureCode)" string
I was able to figure this out. It turns out the context file generated by SP Metal is corrupt. The stack trace pointed out the solution. I removed the __permi(Object , Object ) and it worked perfectly.
Related
In the text file, I create a list for user input their condition, in order to filter out these four value in the excel file.
abc=<>10,<>20,<>30,<>40
And into program, I wrote this to read the list:
try
{
abc = dic["abc"];
if (abc == null || abc.Trim() == "")
{
MessageBox.Show("abc can't be empty!");
this.Close();
}
}
catch (KeyNotFoundException)
{
MessageBox.Show("abc can't be found in Config.txt!");
this.Close();
}
And in the final steps, I want to add the list into string list in my source code, then use autofilter function to filter the excel
string[] abc_list = abc.Split(',');
newSheet.Range["$A:$OO"].AutoFilter(12, abc_list, Excel.XlAutoFilterOperator.xlFilterValues);
And this is the error I got:
23:49:16
Line No.: 5778
System.Runtime.InteropServices.COMException (0x800A03EC): _AutoFilter method of Range class failed
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Range.AutoFilter(Object Field, Object Criteria1, XlAutoFilterOperator Operator, Object Criteria2, Object VisibleDropDown)
But I found that it is not working. Can anyone tell me why?
Thanks.
I found that change .xlFilterValue to .xlOr can solve this question.
I faced the problem with a blow code that i need to change the excel page setup(orientation zoom or any property but the default printer is not available, i didn't have permessions to access printer or found so this code raised exception.
xlApp = new Excel.Application();
book = xlApp.Workbooks.Open(fileFullPath);
xlApp.Visible = false;
xlApp.DisplayAlerts = false;
var with1 = book.Worksheets[sheetName].PageSetup;
with1.zoom = false;
with1.FitToPagesWide = 1;
with1.FitToPagesTall = 1;
with1.Orientation = XlPageOrientation.xlLandscape;
the exception is:
Exception: System.Runtime.InteropServices.COMException
Message: Unable to set the Zoom property of the PageSetup class
Target Site: Void CheckThrowException(Int32, System.Dynamic.ExcepInfo ByRef, UInt32, System.String)
Source: Microsoft Excel
Stack Trace: at System.Dynamic.ComRuntimeHelpers.CheckThrowException(Int32 hresult, ExcepInfo& excepInfo, UInt32 argErr, String message)
at CallSite.Target(Closure , CallSite , ComObject , Boolean )
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
at CallSite.Target(Closure , CallSite , Object , Boolean )
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
at ExcelProcessing.ThumbGeneration.ExcelSheetSnapShoot(String fileFullPath, String thumbDir, String sheetName, String thumbResolution, String cropArea, String PDFFilesDir)
note:
the exception happened when no printers found as default to when change page layout properties throw this exception so i need to any other thing to export excel file as lanscape PDF
This is not an answer, but it wouldn't fit in a comment, so I put it here.
I would like to check if the same steps work from another Excel session instead of C#.
Try to start Excel create this macro and run it. It will create a second Excel session just like your C# function does. I tried in my computer and it works.
If it works, then very likely it's a problem with .net.
If it doesn't, then very likely it's a problem with the file the hidden session is opening.
Sub Test()
Dim Exl As New Application, Wb As Workbook, PS As PageSetup
Set Wb = Exl.Workbooks.Open("Test.xls")
Set PS = Wb.ActiveSheet.PageSetup
PS.Zoom = False
PS.FitToPagesWide = 1
PS.FitToPagesTall = 1
PS.Orientation = XlPageOrientation.xlLandscape
Exl.Quit
End Sub
I have a signed, trusted application in Silverlight 5 (and know its working correctly and AutomationFactory is enabled). However, no matter what I do, I get a COM exception of type mismatch, which is no help, when I try to query the registry. Windows 7 IE8.
{System.Runtime.InteropServices.COMException (0x80041005): Exception from HRESULT: 0x80041005 ---> MS.Internal.ComAutomation.ComAutomationObjectException: Type mismatch
(Source=SWbemObjectEx)
at MS.Internal.ComAutomation.ComAutomationNative.CheckInvokeHResult(UInt32 hr, String memberName, String exceptionSource, String exceptionDescription, String exceptionHelpFile, UInt32 exceptionHelpContext)
at MS.Internal.ComAutomation.ComAutomationNative.Invoke(Boolean tryInvoke, String memberName, ComAutomationInvokeType invokeType, ComAutomationInteropValue[] rgParams, IntPtr nativePeer, ComAutomationInteropValue& returnValue)
at MS.Internal.ComAutomation.ComAutomationObject.InvokeImpl(Boolean tryInvoke, String name, ComAutomationInvokeType invokeType, Object& returnValue, Object[] args)
at MS.Internal.ComAutomation.ComAutomationObject.Invoke(String name, ComAutomationInvokeType invokeType, Object[] args)
at System.Runtime.InteropServices.Automation.AutomationMetaObjectProvider.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)
at System.Runtime.InteropServices.Automation.AutomationMetaObjectProviderBase.<.cctor>b__4(Object obj, InvokeMemberBinder binder, Object[] args)
at CallSite.Target(Closure , CallSite , Object , UInt32 , String , String[]& )
at CallSite.Target(Closure , CallSite , Object , UInt32 , String , String[]& )
Here is my code
uint HKEY_LOCAL_MACHINE = 0x80000002;
var locatorService = AutomationFactory.CreateObject("WbemScripting.SWbemLocator");
var wmiService = locatorService.ConnectServer(".", "root\\DEFAULT");
wmiService.Security_.ImpersonationLevel = 3;
wmiService.Security_.AuthenticationLevel = 4;
var objRegistry = wmiService.Get("StdRegProv");
string strRegIdentityCodes = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
string[] result = null;
objRegistry.EnumKey(HKEY_LOCAL_MACHINE, strRegIdentityCodes, out result);
I think you need to do two changes:
1) change:
uint HKEY_LOCAL_MACHINE = 0x80000002;
to:
int HKEY_LOCAL_MACHINE = unchecked((int)0x80000002);
to avoid the type mismatch error, and
2) change:
string[] result = null;
to:
object[] result = null;
to avoid a forthcoming "System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'System.String[]'"
Not sure where to begin. I have code setup to create a new site and then copy the look, lists, and webparts from a template site.
IT WORKS FINE WHEN LOGGED IN AS SYSTEM ADMIN!
foreach (Microsoft.SharePoint.WebPartPages.WebPart webPartTemplate in webPartCollectionTemplate)
{
try
{
MemoryStream memoryStream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
webPartManagerTemplate.ExportWebPart(webPartTemplate, xmlWriter);
xmlWriter.Flush();
memoryStream.Flush();
memoryStream.Position = 0;
XmlTextReader xmlReader = new XmlTextReader(memoryStream);
Microsoft.SharePoint.WebPartPages.ListViewWebPart listViewWebPartTemplate = null;
Microsoft.SharePoint.WebPartPages.ListViewWebPart listViewWebPartTarget = null;
Microsoft.SharePoint.WebPartPages.WebPart webPartTarget = null;
bool webPartIsListViewWebPart = false;
// If it throws an exception, the web part is not a ListViewWebPart
try
{
listViewWebPartTemplate = (ListViewWebPart)webPartTemplate;
webPartIsListViewWebPart = true;
}
catch { }
if (webPartIsListViewWebPart)
{
string errorMessage = "";
listViewWebPartTarget = (Microsoft.SharePoint.WebPartPages.ListViewWebPart)webPartManagerTarget.ImportWebPart(xmlReader, out errorMessage);
if (errorMessage != null)
// log it
// Drop the brackets from the Guid and create a Guid object from the string. Then use it to find the list so we can get the title.
SPList listTemplate = webTemplate.Lists[new Guid(listViewWebPartTemplate.ListName.ToString().TrimStart('{').TrimEnd('}'))];
SPList listTarget = webTarget.Lists[listTemplate.Title];
listViewWebPartTarget.ListName = listTarget.ID.ToString("B").ToUpper();
listViewWebPartTarget.WebId = webTarget.ID;
listViewWebPartTarget.TitleUrl = webPartTemplate.TitleUrl.ToString().Replace(siteTemplate.ServerRelativeUrl, siteTarget.ServerRelativeUrl);
listViewWebPartTarget.Title = webPartTemplate.Title;
listViewWebPartTarget.ZoneID = webPartTemplate.ZoneID;
webPartDictTarget.Add(listViewWebPartTarget.ZoneID + webPartTemplate.ZoneIndex.ToString(), listViewWebPartTarget);
}
else
{
string errorMessage = "";
webPartTarget = (Microsoft.SharePoint.WebPartPages.WebPart)webPartManagerTarget.ImportWebPart(xmlReader, out errorMessage);
if (errorMessage != null)
// log it
webPartTarget.ChromeType = webPartTemplate.ChromeType;
webPartTarget.TitleUrl = webPartTemplate.TitleUrl.ToString().Replace(siteTemplate.ServerRelativeUrl, siteTarget.ServerRelativeUrl);
webPartTarget.Title = webPartTemplate.Title;
webPartTarget.ZoneID = webPartTemplate.ZoneID;
webPartDictTarget.Add(webPartTarget.ZoneID + webPartTemplate.ZoneIndex.ToString(), webPartTarget);
}
}
catch (Exception ex)
{
}
}
// Acquire keys and sort them.
List<string> list = new List<string>(webPartDictTarget.Keys);
list.Sort();
// Loop through keys.
int i = 0;
foreach (var key in list)
{
try
{
Microsoft.SharePoint.WebPartPages.WebPart wpTmp = (Microsoft.SharePoint.WebPartPages.WebPart)webPartDictTarget[key];
webPartManagerTarget.AddWebPart(wpTmp, wpTmp.ZoneID, i);
}
catch (Exception ex)
{
}
i++;
}
The error is thrown on the following line:
webPartManagerTarget.AddWebPart(wpTmp, wpTmp.ZoneID, i);
The stack trace follows {"There was an error generating the XML document."}:
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter
xmlWriter, Object o, XmlSerializerNamespaces namespaces, String
encodingStyle, String id) at
System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter,
Object o) at
Microsoft.SharePoint.WebPartPages.WebPart.SerializeXml(XmlWriter
writer, XmlSerializer xmls, Boolean shouldSerializeAll) at
Microsoft.SharePoint.WebPartPages.WebPart.WriteXmlAsBytes(XmlSerializer
xmls) at
Microsoft.SharePoint.WebPartPages.WebPart.WriteXmlGlobal(Boolean
disableSafeControlsCheck) at
Microsoft.SharePoint.WebPartPages.BinaryWebPartSerializer.Serialize(PersonalizationScope
scope) at
Microsoft.SharePoint.WebPartPages.BinaryWebPartSerializer.get_Links()
at
Microsoft.SharePoint.WebPartPages.SPWebPartManager.AddWebPartToStore(WebPart
webPart, Int32 viewId, String viewGuid) at
Microsoft.SharePoint.WebPartPages.SPWebPartManager.AddWebPartInternal(SPSupersetWebPart
superset, Boolean throwIfLocked) at
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager.AddWebPartInternal(WebPart
webPart, String zoneId, Int32 zoneIndex, Boolean throwIfLocked) at
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager.AddWebPart(WebPart
webPart, String zoneId, Int32 zoneIndex) at
admSitePanelSolution.admSiteCreateCollection.<>c_DisplayClasse.b_c()
And the InnerException {"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"}:
at
Microsoft.SharePoint.SPGlobal.HandleUnauthorizedAccessException(UnauthorizedAccessException
ex) at
Microsoft.SharePoint.Library.SPRequest.GetViewsSchemaXml(String
bstrUrl, String bstrListName, Boolean bFullBlown, ISP2DSafeArrayWriter
p2DWriter, Int32& plDefaultViewIndex) at
Microsoft.SharePoint.SPViewCollection.EnsureViewSchema(Boolean
fullBlownSchema) at
Microsoft.SharePoint.SPViewCollection..ctor(SPList list) at
Microsoft.SharePoint.SPList.get_Views() at
Microsoft.SharePoint.SPList.get_DefaultView() at
Microsoft.SharePoint.SPList.get_DefaultViewUrl() at
Microsoft.SharePoint.WebPartPages.ListViewWebPart.ShouldSerializeDetailLink()
at
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterListViewWebPart.Write9_ListViewWebPart(String
n, String ns, ListViewWebPart o, Boolean isNullable, Boolean needType)
at
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterListViewWebPart.Write10_WebPart(Object
o)
Can anyone provide some help of why this happens when not logged in as system admin. This whole block also runs inside elevated privileges and the SPSite and SPWeb were also instantiated inside the elevated block. This code is an excerpt.
UPDATE
If I make the user a site collection owner of the base site collection, then the code above runs fine. So what in the code above resets context or needs to reference the base site collection. Thank you.
And my colleague swoops in to save the day! In SP dev, there is a well known 'hack' which is used a lot when permissions get weird and stupid. It is to nullify the HttpContext. I tried this around the line and loop which was giving me an issue but it appears that you have to place it much higher in the code during the import.
Here is the new fix.
HttpContext currentContext = HttpContext.Current;
HttpContext.Current = null;
listViewWebPartTarget = (Microsoft.SharePoint.WebPartPages.ListViewWebPart)webPartManagerTarget.ImportWebPart(xmlReader, out errorMessage);
HttpContext.Current = currentContext;
This code now works for copying webparts from one apsx page to another. Hope it helps someone.
I am trying to call the GetReportParameters method from the ReportingServices2005.asmx web service from another C# function and I am getting the following error:
System.NotImplementedException: The method or operation is not implemented.
I litterally just copied the code from Microsoft's site here:
Get Parameters Example
which is this code:
bool forRendering = false;
string historyID = null;
ParameterValue[] values = null;
DataSourceCredentials[] credentials = null;
ReportParameter[] parameters = null;
try
{
parameters = rs.GetReportParameters(reportName,historyID, forRendering, values,credentials);
if (parameters != null)
{
foreach (ReportParameter rp in parameters)
{
Console.WriteLine("Name: {0}", rp.Name);
}
}
}
catch (SoapException e)
{
error = e.Detail.InnerXml.ToString();
}
Where reportName is a string with the name of the report.
Any ideas??
Thanks in advance!
EDIT
Here is the full stack trace:
System.NotImplementedException: The method or operation is not implemented.
at Foo.Foo.ReportingService2005.GetReportParameters(String reportName, String historyID, Boolean forRendering, ParameterValue[] values, DataSourceCredentials[] credentials) in C:\Visual Studio Projects\Foo\Foo\Web References\Foo\Reference.cs:line 4112
at Foo.Foo.GetReportParameters(String username, String password, String reportName) in C:\Visual Studio Projects\Foo\Foo\Foo.asmx.cs:line 265
I deleted and re-added the Web Reference and this didn't do the trick, but after lots of trial and error I noticed that
ParameterValue[] values = null;
DataSourceCredentials[] credentials = null;
ReportParameter[] parameters = null;
Were all referencing another Web Reference.... Not even sure how that's possible.. But, I deleted the other Web Reference that had nothing to do with Reporting Services and all is now working.