Role based Login in liferay? - liferay

How can I implement Role based Login in Liferay. I have already created a Login Hook which redirects users to their site at the time of login.
Ex:
User 1 will got to site 1.
User 2 will got to site 1.
User 3 will got to site 2.
User 4 will got to site 2.
and if a user is not assigned to any site, will be directed to default login site.
Now, What I want is if User 1(role = administrator) Logs in should be redirected to page 1(administrator page) of site 1.
and User 2(role = manager) Logs in should be redirected to page 2(manager page) of site 1.
Based on their roles. Can this be possible ?. If yes please help regarding this as how to implement it.
I'll add my code below.
#Component
(
immediate = true,
property =
{
"key=login.events.post"
},
service = LifecycleAction.class
)
public class MyCustomLoginHookLoginPostAction extends Action
{
private final static String PUBLIC_PAGE_CONTEXT = "/web";
private final static String PRIVATE_PAGE_CONTEXT = "/group";
#Override
public void run(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ActionException
{
final long companyId = PortalUtil.getCompanyId(httpServletRequest);
String path = PrefsPropsUtil.getString(companyId, PropsKeys.DEFAULT_LANDING_PAGE_PATH);
try
{
path = getCustomLandingPage(httpServletRequest);
}
catch (PortalException e)
{
throw new ActionException(e);
}
if(Validator.isNotNull(path))
{
final HttpSession httpSession = httpServletRequest.getSession();
httpSession.setAttribute(WebKeys.LAST_PATH, new LastPath(StringPool.BLANK, path));
}
}
private String getCustomLandingPage(HttpServletRequest httpServletRequest) throws PortalException
{
String path = null;
User user = PortalUtil.getUser(httpServletRequest);
List<Organization> orgs = user.getOrganizations();
if(orgs != null && !orgs.isEmpty())
{
for(Organization org : orgs)
{
Group orgSite = org.getGroup();
int publicPageCount = orgSite.getPublicLayoutsPageCount();
int privatePageCount = orgSite.getPrivateLayoutsPageCount();
if(publicPageCount > 0)
{
path = PUBLIC_PAGE_CONTEXT+ orgSite.getFriendlyURL();
break;
}
else if(privatePageCount > 0)
{
path = PRIVATE_PAGE_CONTEXT + orgSite.getFriendlyURL();
break;
}
}
}
if(Validator.isNull(path))
{
List<Group> sites = user.getGroups();
if(sites != null && !sites.isEmpty())
{
for(Group site : sites)
{
int publicPageCount = site.getPublicLayoutsPageCount();
int privatePageCount = site.getPrivateLayoutsPageCount();
if(publicPageCount > 0)
{
path = PUBLIC_PAGE_CONTEXT + site.getFriendlyURL();
break;
}
else if(privatePageCount > 0)
{
path = PRIVATE_PAGE_CONTEXT + site.getFriendlyURL();
break;
}
}
}
}
if(Validator.isNull(path))
{
path = PrefsPropsUtil.getString(PortalUtil.getCompanyId(httpServletRequest), PropsKeys.DEFAULT_LANDING_PAGE_PATH);
}
return path;
}
}
EDIT: after the answer
2022-08-24 09:23:22.822 ERROR [http-nio-8080-exec-2][MainServlet:526] java.lang.NullPointerException
java.lang.NullPointerException
at my.custom.login.hook.MyCustomLoginHookLoginPostAction.getCustomLandingPage(MyCustomLoginHookLoginPostAction.java:847)
at my.custom.login.hook.MyCustomLoginHookLoginPostAction.run(MyCustomLoginHookLoginPostAction.java:826)
at com.liferay.portal.kernel.events.InvokerAction.run(InvokerAction.java:41)
at com.liferay.portal.kernel.events.Action.processLifecycleEvent(Action.java:34)
at com.liferay.portal.events.EventsProcessorUtil.process(EventsProcessorUtil.java:98)
at com.liferay.portal.events.EventsProcessorUtil.process(EventsProcessorUtil.java:60)
at com.liferay.portal.servlet.MainServlet.loginUser(MainServlet.java:1054)
at com.liferay.portal.servlet.MainServlet.service(MainServlet.java:518)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:119)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:103)
at com.liferay.portal.apio.internal.architect.servlet.filter.APIDocumentationFilter.processFilter(APIDocumentationFilter.java:74)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.strip.StripFilter.processFilter(StripFilter.java:340)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.servlet.filters.password.modified.PasswordModifiedFilter.processFilter(PasswordModifiedFilter.java:57)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.secure.BaseAuthFilter.processFilter(BaseAuthFilter.java:340)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.sharepoint.SharepointFilter.processFilter(SharepointFilter.java:88)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter.processFilter(VirtualHostFilter.java:263)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.monitoring.internal.servlet.filter.MonitoringFilter.processFilter(MonitoringFilter.java:178)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:188)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:188)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:389)
at com.liferay.portal.servlet.filters.urlrewrite.UrlRewriteFilter.processFilter(UrlRewriteFilter.java:65)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:168)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:168)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:188)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:101)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:764)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1388)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Faulty Line
String path = null;
final long companyId = PortalUtil.getCompanyId(httpServletRequest);
User user = PortalUtil.getUser(httpServletRequest);
//getting role IDs
// THIS LINE Role roleAdministrator = roleLocalService.fetchRole(companyId, "Administrator");
Role roleManager = roleLocalService.fetchRole(companyId, "Manager");
if(roleLocalService.hasUserRole(user.getUserId(), roleAdministrator.getRoleId()))
{
//has adminrole
}
if(roleLocalService.hasUserRole(user.getUserId(), roleManager.getRoleId()))
{
//has adminrole
}

Sure. You can check roles with the RoleLocalService.
#Component
(
immediate = true,
property =
{
"key=login.events.post"
},
service = LifecycleAction.class
)
public class MyCustomLoginHookLoginPostAction extends Action
{
private final static String PUBLIC_PAGE_CONTEXT = "/web";
private final static String PRIVATE_PAGE_CONTEXT = "/group";
#Override
public void run(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ActionException
{
final long companyId = PortalUtil.getCompanyId(httpServletRequest);
String path = PrefsPropsUtil.getString(companyId, PropsKeys.DEFAULT_LANDING_PAGE_PATH);
try
{
path = getCustomLandingPage(httpServletRequest);
}
catch (PortalException e)
{
throw new ActionException(e);
}
if(Validator.isNotNull(path))
{
final HttpSession httpSession = httpServletRequest.getSession();
httpSession.setAttribute(WebKeys.LAST_PATH, new LastPath(StringPool.BLANK, path));
}
}
private String getCustomLandingPage(HttpServletRequest httpServletRequest) throws PortalException
{
String path = null;
final long companyId = PortalUtil.getCompanyId(httpServletRequest);
User user = PortalUtil.getUser(httpServletRequest);
//getting role IDs
Role roleAdministrator = RoleLocalServiceUtil.fetchRole(companyId, "Administrator");
Role roleManager = RoleLocalServiceUtil.fetchRole(companyId, "Manager");
if(RoleLocalServiceUtil.hasUserRole(user.getUserId(), roleAdministrator.getRoleId())) {
//has adminrole
}
if(RoleLocalServiceUtil.hasUserRole(user.getUserId(), roleManager.getRoleId())) {
//has adminrole
}
List<Organization> orgs = user.getOrganizations();
if(orgs != null && !orgs.isEmpty())
{
for(Organization org : orgs)
{
Group orgSite = org.getGroup();
int publicPageCount = orgSite.getPublicLayoutsPageCount();
int privatePageCount = orgSite.getPrivateLayoutsPageCount();
if(publicPageCount > 0)
{
path = PUBLIC_PAGE_CONTEXT+ orgSite.getFriendlyURL();
break;
}
else if(privatePageCount > 0)
{
path = PRIVATE_PAGE_CONTEXT + orgSite.getFriendlyURL();
break;
}
}
}
if(Validator.isNull(path))
{
List<Group> sites = user.getGroups();
if(sites != null && !sites.isEmpty())
{
for(Group site : sites)
{
int publicPageCount = site.getPublicLayoutsPageCount();
int privatePageCount = site.getPrivateLayoutsPageCount();
if(publicPageCount > 0)
{
path = PUBLIC_PAGE_CONTEXT + site.getFriendlyURL();
break;
}
else if(privatePageCount > 0)
{
path = PRIVATE_PAGE_CONTEXT + site.getFriendlyURL();
break;
}
}
}
}
if(Validator.isNull(path))
{
path = PrefsPropsUtil.getString(PortalUtil.getCompanyId(httpServletRequest), PropsKeys.DEFAULT_LANDING_PAGE_PATH);
}
return path;
}
}

Related

Android Licensing plugin I have being remaking has logcat error: java.lang.ClassNotFoundException, only on release build not development build

So I have being trying to make this plugin work:
https://github.com/Unity-Technologies/GooglePlayLicenseVerification
Really I'm surprised of how much of challenge it's being since this is suppose to be just a basic functionality that millions of android apps/games must have.
I tried tones of things to make it work wasn't sure what was going on why it wasn't working so I decided maybe I should try to remake the plugin with android studio. So I can rebuild it.
I got to the point where I can make a test plugin work that just prints something in the console but it only works when I make a unity development build. When I make a release build I get in logcat error java.lang.ClassNotFoundException (below i put the full error message)
In the development mode the licensing plugin doesn't give any logcat errors but it doesn't work either. I figured that probably the reason it doesn't work is linked to the reason the release mode is giving me an error.
Here is some important info of how I'm doing things.
I'm making the plugin by building a .aar file in android studio. That I copy in to the:
\Assets\Plugins\Android\libs folder.
it's name is : unity-release.aar
when I build I make Build App Bundle (google play) since that's my end goal. but if i build an apk i have the same issue.
I tried to match the unity android player settings like minimum api with the build gradle.
So here is my java file for the licensing plugin:
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class ServiceBinder extends android.os.Binder implements ServiceConnection
{
private final Context mContext;
private static String PrintTag = "Licensing";
public ServiceBinder(Context context)
{
mContext = context;
}
private Runnable mDone = null;
private int mNonce;
public void create(int nonce, Runnable done)
{
if (mDone != null)
{
Log.i(PrintTag,"mDone != null");
destroy();
_arg0 = -1;
mDone.run();
}
mNonce = nonce;
mDone = done;
Intent serviceIntent = new Intent(SERVICE);
serviceIntent.setPackage("com.android.vending");
if (mContext.bindService(serviceIntent, this, Context.BIND_AUTO_CREATE)){
Log.i(PrintTag,"mContext.bindService(..)true");
return;
}
Log.i(PrintTag,"mContext.bindService(..)false");
mDone.run();
}
private void destroy()
{
mContext.unbindService(this);
}
private static final String SERVICE = "com.android.vending.licensing.ILicensingService";
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(PrintTag,"onServiceConnected called 0");
android.os.Parcel _data = android.os.Parcel.obtain();
_data.writeInterfaceToken(SERVICE);
_data.writeLong(mNonce);
_data.writeString(mContext.getPackageName());
_data.writeStrongBinder(this);
Log.i(PrintTag,"onServiceConnected called 1");
try {
Log.i(PrintTag,"service.transact called");
service.transact(1/*Stub.TRANSACTION_checkLicense*/, _data, null, IBinder.FLAG_ONEWAY);
}
catch (Exception ex)
{
ex.printStackTrace();
Log.i(PrintTag,"Exception called ex.printStackTrace();");
}
finally {
_data.recycle();
Log.i(PrintTag,"finally _data.recycle();");
}
}
private static final String LISTENER = "com.android.vending.licensing.ILicenseResultListener";
public boolean onTransact(int code, android.os.Parcel data,
android.os.Parcel reply, int flags)
throws android.os.RemoteException {
Log.i(PrintTag,"onTransact called");
switch (code) {
case INTERFACE_TRANSACTION: {
Log.i(PrintTag,"switch INTERFACE_TRANSACTION ");
reply.writeString(LISTENER);
return true;
}
case 1/*TRANSACTION_verifyLicense*/: {
Log.i(PrintTag,"switch 1 ");
data.enforceInterface(LISTENER);
_arg0 = data.readInt();
_arg1 = data.readString();
_arg2 = data.readString();
mDone.run();
destroy();
return true;
}
}
Log.i(PrintTag,"return super.onTransact(code, data, reply, flags)");
return super.onTransact(code, data, reply, flags);
}
public void onServiceDisconnected(ComponentName name) {
}
int _arg0;
String _arg1;
String _arg2;
}
Here is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.PlayStore.plugin.unity">
<application
android:allowBackup="true"
android:label="#string/app_name"
android:supportsRtl="true"
/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.android.vending.CHECK_LICENSE"/>
</manifest>
here is my project build.gadle file:
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.4"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
here is my module gradle.build file:
plugins {
id 'com.android.application'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.unity3d.plugin.lvl"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
here is the unity file that uses the plugin:
another class calls the Init() method then the VerifyLicense() methode.
using System;
using UnityEngine;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine.Networking;
using UnityEngine.UI;
using Random = System.Random;
public class CheckLVLButton : MonoBehaviour
{
public Text printText;
/*
* Use the public LVL key from the Android Market publishing section here.
*/
[SerializeField] [Tooltip("Insert LVL public key here")]
private string m_PublicKey_Base64 = string.Empty;
/*
* Consider storing the public key as RSAParameters.Modulus/.Exponent rather than Base64 to prevent the ASN1 parsing..
* These are printed to the logcat below.
*/
[SerializeField] [Tooltip("Filled automatically when you input a valid LVL public key above")]
private string m_PublicKey_Modulus_Base64 = string.Empty;
[SerializeField] [Tooltip("Filled automatically when you input a valid LVL public key above")]
private string m_PublicKey_Exponent_Base64 = string.Empty;
const string pluginName = "com.PlayStore.plugin.unity.ServiceBinder";
[SerializeField]
private Text resultsTextArea = default;
private RSAParameters m_PublicKey;
private Random _random;
private AndroidJavaObject m_Activity;
private AndroidJavaObject m_LVLCheck;
bool licenceConfirmed = false;
public void Init()
{
Debug.Log("hello are my in android?");
printText.text += "\n-started app";
Debug.unityLogger.Log(BrandDisplay.LOG_TAG_LICENSING, "Init licensing---");
if (string.IsNullOrEmpty(m_PublicKey_Modulus_Base64) || string.IsNullOrEmpty(m_PublicKey_Exponent_Base64))
{
DisplayError("Please input a valid LVL public key in the inspector to generate its modulus and exponent");
return;
}
bool isRunningInAndroid = new AndroidJavaClass("android.os.Build").GetRawClass() != IntPtr.Zero;
if (isRunningInAndroid == false)
{
DisplayError("Please run this on an Android device!");
return;
}
_random = new Random();
m_PublicKey.Modulus = Convert.FromBase64String(m_PublicKey_Modulus_Base64);
m_PublicKey.Exponent = Convert.FromBase64String(m_PublicKey_Exponent_Base64);
m_Activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
m_PackageName = m_Activity.Call<string>("getPackageName");
printText.text += "\n-end started app";
Debug.unityLogger.Log(BrandDisplay.LOG_TAG_LICENSING, "end Init licensing---");
}
private void OnValidate()
{
if (string.IsNullOrEmpty(m_PublicKey_Base64) == false)
{
try
{
RSA.SimpleParseASN1(m_PublicKey_Base64, ref m_PublicKey.Modulus, ref m_PublicKey.Exponent);
}
catch (Exception e)
{
Debug.LogError($"Please input a valid LVL public key in the inspector to generate its modulus and exponent\n{e.Message}");
return;
}
// The reason we keep the modulus and exponent is to avoid a costly call to SimpleParseASN1 at runtime
m_PublicKey_Modulus_Base64 = Convert.ToBase64String(m_PublicKey.Modulus);
m_PublicKey_Exponent_Base64 = Convert.ToBase64String(m_PublicKey.Exponent);
m_PublicKey_Base64 = string.Empty;
}
}
public bool VerifyLicense()
{
m_Nonce = _random.Next();
string results = "<b>Requesting LVL response...</b>\n" +
$"Package name: {m_PackageName}\n" +
$"Request nonce: 0x{m_Nonce:X}";
DisplayResults(results);
printText.text += "\n-verifyLicense";
Debug.unityLogger.Log(BrandDisplay.LOG_TAG_LICENSING, "verifyLicense---");
m_LVLCheck = new AndroidJavaObject(pluginName, m_Activity);
m_LVLCheck.Call("create", m_Nonce, new AndroidJavaRunnable(Process));
Debug.unityLogger.Log(BrandDisplay.LOG_TAG_LICENSING, "EndverifyLicense---");
printText.text += "\n-EndverifyLicense";
return licenceConfirmed;
}
private string m_PackageName;
private int m_Nonce;
private string m_ResponseCode_Received;
private string m_PackageName_Received;
private int m_Nonce_Received;
private int m_VersionCode_Received;
private string m_UserID_Received;
private string m_Timestamp_Received;
private int m_MaxRetry_Received;
private string m_LicenceValidityTimestamp_Received;
private string m_GracePeriodTimestamp_Received;
private string m_UpdateTimestamp_Received;
private string m_FileURL1_Received = string.Empty;
private string m_FileURL2_Received = string.Empty;
private string m_FileName1_Received;
private string m_FileName2_Received;
private int m_FileSize1_Received;
private int m_FileSize2_Received;
private string m_LicensingURL_Received = string.Empty;
private static Dictionary<string, string> DecodeExtras(string query)
{
Dictionary<string, string> result = new Dictionary<string, string>();
if (query.Length == 0)
return result;
string decoded = query;
int decodedLength = decoded.Length;
int namePos = 0;
bool first = true;
while (namePos <= decodedLength)
{
int valuePos = -1, valueEnd = -1;
for (int q = namePos; q < decodedLength; q++)
{
if (valuePos == -1 && decoded[q] == '=')
{
valuePos = q + 1;
}
else if (decoded[q] == '&')
{
valueEnd = q;
break;
}
}
if (first)
{
first = false;
if (decoded[namePos] == '?')
namePos++;
}
string name;
if (valuePos == -1)
{
name = string.Empty;
valuePos = namePos;
}
else
{
name = UnityWebRequest.UnEscapeURL(decoded.Substring(namePos, valuePos - namePos - 1));
}
if (valueEnd < 0)
{
namePos = -1;
valueEnd = decoded.Length;
}
else
{
namePos = valueEnd + 1;
}
string value = UnityWebRequest.UnEscapeURL(decoded.Substring(valuePos, valueEnd - valuePos));
result.Add(name, value);
if (namePos == -1)
break;
}
return result;
}
private Int64 ConvertEpochSecondsToTicks(Int64 secs)
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
Int64 seconds_to_100ns_ticks = 10 * 1000;
Int64 max_seconds_allowed = (DateTime.MaxValue.Ticks - epoch.Ticks)
/ seconds_to_100ns_ticks;
if (secs < 0)
secs = 0;
if (secs > max_seconds_allowed)
secs = max_seconds_allowed;
return epoch.Ticks + secs * seconds_to_100ns_ticks;
}
private void Process()
{
string results = "<b>Requested LVL response</b>\n" +
$"Package name: {m_PackageName}\n" +
$"Request nonce: 0x{m_Nonce:X}\n" +
"------------------------------------------\n" +
"<b>Received LVL response</b>\n";
printText.text += "\n-process called";
Debug.Log("process called");
Debug.unityLogger.Log(BrandDisplay.LOG_TAG_LICENSING, "process called-----");
if (m_LVLCheck == null)
{
results += "m_LVLCheck is null!";
DisplayResults(results);
return;
}
int responseCode = m_LVLCheck.Get<int>("_arg0");
string message = m_LVLCheck.Get<string>("_arg1");
string signature = m_LVLCheck.Get<string>("_arg2");
m_LVLCheck.Dispose();
m_LVLCheck = null;
m_ResponseCode_Received = responseCode.ToString();
if (responseCode < 0 || string.IsNullOrEmpty(message) || string.IsNullOrEmpty(signature))
{
results += "Package name: <Failed>";
licenceConfirmed = false;
DisplayResults(results);
return;
}
byte[] message_bytes = System.Text.Encoding.UTF8.GetBytes(message);
byte[] signature_bytes = Convert.FromBase64String(signature);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
csp.ImportParameters(m_PublicKey);
SHA1Managed sha1 = new SHA1Managed();
bool match = csp.VerifyHash(sha1.ComputeHash(message_bytes), CryptoConfig.MapNameToOID("SHA1"), signature_bytes);
if (!match)
{
results += "Response code: <Failed>" +
"Package name: <Invalid Signature>";
DisplayResults(results);
licenceConfirmed = false;
return;
}
int index = message.IndexOf(':');
string mainData, extraData;
if (-1 == index)
{
mainData = message;
extraData = string.Empty;
}
else
{
mainData = message.Substring(0, index);
extraData = index >= message.Length ? string.Empty : message.Substring(index + 1);
}
string[] vars = mainData.Split('|'); // response | nonce | package | version | userid | timestamp
if (String.Compare(vars[0], responseCode.ToString(), StringComparison.Ordinal) != 0)
{
results += "Response code: <Failed>" +
"Package name: <Invalid Mismatch>";
DisplayResults(results);
licenceConfirmed = false;
return;
}
m_ResponseCode_Received = vars[0];
m_Nonce_Received = Convert.ToInt32(vars[1]);
m_PackageName_Received = vars[2];
m_VersionCode_Received = Convert.ToInt32(vars[3]);
m_UserID_Received = vars[4];
Int64 ticks = ConvertEpochSecondsToTicks(Convert.ToInt64(vars[5]));
m_Timestamp_Received = new DateTime(ticks).ToLocalTime().ToString();
if (!string.IsNullOrEmpty(extraData))
{
Dictionary<string, string> extrasDecoded = DecodeExtras(extraData);
if (extrasDecoded.ContainsKey("GR"))
{
m_MaxRetry_Received = Convert.ToInt32(extrasDecoded["GR"]);
}
else
{
m_MaxRetry_Received = 0;
}
if (extrasDecoded.ContainsKey("VT"))
{
ticks = ConvertEpochSecondsToTicks(Convert.ToInt64(extrasDecoded["VT"]));
m_LicenceValidityTimestamp_Received = new DateTime(ticks).ToLocalTime().ToString();
}
else
{
m_LicenceValidityTimestamp_Received = null;
}
if (extrasDecoded.ContainsKey("GT"))
{
ticks = ConvertEpochSecondsToTicks(Convert.ToInt64(extrasDecoded["GT"]));
m_GracePeriodTimestamp_Received = new DateTime(ticks).ToLocalTime().ToString();
}
else
{
m_GracePeriodTimestamp_Received = null;
}
if (extrasDecoded.ContainsKey("UT"))
{
ticks = ConvertEpochSecondsToTicks(Convert.ToInt64(extrasDecoded["UT"]));
m_UpdateTimestamp_Received = new DateTime(ticks).ToLocalTime().ToString();
}
else
{
m_UpdateTimestamp_Received = null;
}
if (extrasDecoded.ContainsKey("FILE_URL1"))
{
m_FileURL1_Received = extrasDecoded["FILE_URL1"];
}
else
{
m_FileURL1_Received = "";
}
if (extrasDecoded.ContainsKey("FILE_URL2"))
{
m_FileURL2_Received = extrasDecoded["FILE_URL2"];
}
else
{
m_FileURL2_Received = "";
}
if (extrasDecoded.ContainsKey("FILE_NAME1"))
{
m_FileName1_Received = extrasDecoded["FILE_NAME1"];
}
else
{
m_FileName1_Received = null;
}
if (extrasDecoded.ContainsKey("FILE_NAME2"))
{
m_FileName2_Received = extrasDecoded["FILE_NAME2"];
}
else
{
m_FileName2_Received = null;
}
if (extrasDecoded.ContainsKey("FILE_SIZE1"))
{
m_FileSize1_Received = System.Convert.ToInt32(extrasDecoded["FILE_SIZE1"]);
}
else
{
m_FileSize1_Received = 0;
}
if (extrasDecoded.ContainsKey("FILE_SIZE2"))
{
m_FileSize2_Received = System.Convert.ToInt32(extrasDecoded["FILE_SIZE2"]);
}
else
{
m_FileSize2_Received = 0;
}
if (extrasDecoded.ContainsKey("LU"))
{
m_LicensingURL_Received = extrasDecoded["LU"];
}
else
{
m_LicensingURL_Received = "";
}
}
results += $"Response code: {m_ResponseCode_Received}\n" +
$"Package name: {m_PackageName_Received}\n" +
$"Received nonce: 0x{m_Nonce_Received:X}\n" +
$"Version code: {m_VersionCode_Received}\n" +
$"User ID: {m_UserID_Received}\n" +
$"Timestamp: {m_Timestamp_Received}\n" +
$"Max Retry: {m_MaxRetry_Received}\n" +
$"License Validity: {m_LicenceValidityTimestamp_Received}\n" +
$"Grace Period: {m_GracePeriodTimestamp_Received}\n" +
$"Update Since: {m_UpdateTimestamp_Received}\n" +
$"Main OBB URL: {m_FileURL1_Received.Substring(0, Mathf.Min(m_FileURL1_Received.Length,50)) + "..."}\n" +
$"Main OBB Name: {m_FileName1_Received}\n" +
$"Main OBB Size: {m_FileSize1_Received}\n" +
$"Patch OBB URL: {m_FileURL2_Received.Substring(0, Mathf.Min(m_FileURL2_Received.Length,50)) + "..."}\n" +
$"Patch OBB Name: {m_FileName2_Received}\n" +
$"Patch OBB Size: {m_FileSize2_Received}\n" +
$"Licensing URL: {m_LicensingURL_Received.Substring(0, Mathf.Min(m_LicensingURL_Received.Length,50)) + "..."}\n";
DisplayResults(results);
licenceConfirmed = true;
printText.text += "\n-process finished";
}
private void DisplayResults(string text)
{
Debug.Log(text);
resultsTextArea.text = text;
}
private void DisplayError(string text)
{
resultsTextArea.text = text;
Debug.LogError(text);
}
}
Full logcat error I get when building in release. using the Android Device Monitor
03-14 16:40:09.246: E/Unity(16433): AndroidJavaException: java.lang.ClassNotFoundException: com.PlayStore.plugin.unity.ServiceBinder
03-14 16:40:09.246: E/Unity(16433): java.lang.ClassNotFoundException: com.PlayStore.plugin.unity.ServiceBinder
03-14 16:40:09.246: E/Unity(16433): at java.lang.Class.classForName(Native Method)
03-14 16:40:09.246: E/Unity(16433): at java.lang.Class.forName(Class.java:454)
03-14 16:40:09.246: E/Unity(16433): at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
03-14 16:40:09.246: E/Unity(16433): at com.unity3d.player.UnityPlayer.access$300(Unknown Source:0)
03-14 16:40:09.246: E/Unity(16433): at com.unity3d.player.UnityPlayer$e$1.handleMessage(Unknown Source:83)
03-14 16:40:09.246: E/Unity(16433): at android.os.Handler.dispatchMessage(Handler.java:103)
03-14 16:40:09.246: E/Unity(16433): at android.os.Looper.loop(Looper.java:225)
03-14 16:40:09.246: E/Unity(16433): at com.unity3d.player.UnityPlayer$e.run(Unknown Source:20)
03-14 16:40:09.246: E/Unity(16433): Caused by: java.lang.ClassNotFoundException: com.PlayStore.plugin.unity.ServiceBinder
03-14 16:40:09.246: E/Unity(16433): ... 8 more
03-14 16:40:09.246: E/Unity(16433): at UnityEngine.AndroidJNISafe.CheckException () [0x00096] in <18c3cbae8278498a88f31fc7b855af9e>:0
03-14 16:40:09.246: E/Unity(16433): at UnityEngine.AndroidJNISafe.FindClass (System.String name) [0x0000c] in <18c3cbae8278498a88f31fc7b855af9e>:0
03-14 16:40:09.246: E/Unity(16433): at UnityEngine.AndroidJavaObject._AndroidJavaObject (System.String className, System
So completely thx to Jaimin that helped me in the comment I found the fix to my issue.
All I had to do was go to the unity project setting,player,publishing settings and untick minify on release. The whole plugin worked directly after the fix.
I'm not sure if this is the most clean solution. It's maybe better to change the proguard-rules.pro file so it minifies in a way as to not break the code. For the info, minifying changes the code identifiers names so they are shorter and take less space. For my project the unity player settings seem to override settings concerning minifying that where in the gradle build file:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
I'm a developer of a paid 'Google Play License Check' plugin. I struggled for years using the GooglePlayLicenseVerification repo, so I decided to create my own clean and simple API. Using my plugin, you can check the Google Play license by simply calling this:
GooglePlayLicense.Check(license => {
if (license.status == LicenseStatus.NOT_LICENSED) {
Debug.Log("YOU ARE A PIRATE, SHAME ON YOU!");
}
});
After performing the license check, the plugin will cache the response and store it in the PlayerPrefs. To access the cached license:
var cachedLicense = GooglePlayLicense.cachedLicense;
if (cachedLicense != null) {
Debug.Log($"License is valid: {cachedLicense.isLicenseValid}. Grace period: {cachedLicense.gracePeriodTimestamp}.");
}
To add extra protection to your app, you can provide your custom secure storage instead of using PlayerPrefs:
GooglePlayLicense.SetPersistentStorageImplementation(MyAwesomeSecureStorage.SaveString, MyAwesomeSecureStorage.LoadString);
My plugin is available on the Asset Store. Please feel free to ask more questions here or in my plugin's FAQ.

How to add search filters to the last page in a recyclerview that is per page?

I am doing a search filter by identity document in a Recyclerview that is per page, the problem is that at the time of making the filter it only looks for the first 10 that is the current page. How would I filter the search from the current page to the last page?
RecyclerActasAdapter.java
#Override
public int getItemCount() {
return this.itemsMostrados.size();
}
public void filtrar(String query) {
this.itemsMostrados = new ArrayList<>();
if (query.length() == 0) {
itemsMostrados = listaActas;
layoutResultados.setVisibility(View.GONE);
} else {
ActasActivity actas= new ActasActivity();
for (Datum data: listaActas) {
if (data.getBeneficiario().getNumDocumento().contains(query)
//|| (data.getBeneficiario().getNombre().toLowerCase() + " " + data.getBeneficiario().getApellido().toLowerCase()).contains(text.toLowerCase())
|| (data.getBeneficiario() != null ? data.getBeneficiario().getNombre() : "No registra" + " " + data.getBeneficiario() != null ? data.getBeneficiario().getApellido() : "No registra").contains(query)
//|| data.getPoblacion().getNombre().toLowerCase().contains(text.toLowerCase())
//|| data.getMunicipio().getMunicipio().toLowerCase().contains(text.toLowerCase())
) {
itemsMostrados.add(data);
}
}
layoutResultados.setVisibility(View.VISIBLE);
txtResults.setText(itemsMostrados.size() + "");
}
notifyDataSetChanged();
}
public void actualizar() {
itemsMostrados = listaActas;
notifyDataSetChanged();
}
ActasActivity.java
In this activity I try to create the condition to filter search to the last page but still continue to filter only the first 10 of the current page
public void obtenerActas(boolean inicializar) {
if (inicializar) {
current_page = 1;
last_page = 1;
last_size_pages = 0;
}
final Promise<RespuestaActasDTO, BusinessException, RespuestaActasDTO> mPromise = actasService.obtenerActas(current_page);
mPromise.done(result -> {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
actualizarListadoActas(result, inicializar);
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
});
mPromise.fail(error -> {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
Toast.makeText(mContexto, "Ocurrió un error consultando las actas", Toast.LENGTH_SHORT).show();
});
}
public void actualizarListadoActas(RespuestaActasDTO respuestaActasDTO, boolean inicializar) {
// logica para controlar la pagina a consumir y saber cual es la ultima pagina
last_page = respuestaActasDTO.getLastPage();
//SI PAGINA ACTUAL ES MENOR QUE ULTIMA PAGINA
if (current_page < last_page) {
current_page++;//ENUMEREME DESDE LA PAGINA ACTUAL
}
if (actasAdapter == null || inicializar) {
listaActas = new ArrayList<>();
listaActas = respuestaActasDTO.getData();
actasAdapter = new RecyclerActasAdapter(mContexto, listaActas, layoutResultados, txtResults);
recyclerViewActas.setAdapter(actasAdapter);
scrollListener.resetState();
} else {
//página actual < última página
if (current_page < last_page) {
listaActas.addAll(respuestaActasDTO.getData());
actasAdapter.actualizar();
agregarUltimaConsulta = true;
} else if (current_page == last_page) {
if (agregarUltimaConsulta) {
agregarUltimaConsulta = false;
last_size_pages = respuestaActasDTO.getData().size();
ultimaLista = respuestaActasDTO.getData();
listaActas.addAll(ultimaLista);
actasAdapter.actualizar();
} else if (last_size_pages != respuestaActasDTO.getData().size()) {
// limpiar ultimos registros para volverlos a agregar
ultimaLista = respuestaActasDTO.getData();
last_size_pages = respuestaActasDTO.getData().size();
listaActas.addAll(ultimaLista);
actasAdapter.actualizar();
}
}
}
// Logical END to control the page to consume and know which is the last page ------>>>>
if (agregarEventoBuscar) {
agregarEventoBuscar = false;
// buscador
inputBuscar.setOnQueryTextListener( new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
actasAdapter.filtrar(inputBuscar.getQuery().toString() );
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
} );
}
Observation: I only filter the query if I scroll to the last page, Thanks for your support

Saving data read from sql database

I have four textboxes and a metrogrid, inside the textboxes data is read into them from sql database, but while saving the data in the textboxes one will save and others will vanish. Please i need help
this is the code for search button:
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection connection = new SqlConnection(#"server = .\sql2012; database = dbAcceptance; integrated security = true; "))
{
SqlCommand command = new SqlCommand($"select * from acceptance WHERE regno = {txtregno.Text}", connection);
connection.Open();
SqlDataReader read = command.ExecuteReader();
if (read.Read())
{
txtfullname.Text = (read["fullname"].ToString());
txtdepartment.Text = (read["Department"].ToString());
txtfaculty.Text = (read["faculty"].ToString());
txtmodeofstudy.Text = (read["modeofstudy"].ToString());
txtprogramme.Text = (read["programmeofstudy"].ToString());
}
else
MetroFramework.MetroMessageBox.Show(this, "Reg No Not Found...Please Try Again", "Message");
read.Close();
}
}
catch (Exception ex)
{
//MetroFramework.MetroMessageBox.Show(this, ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This is the code for add button:
private void btnAdd_Click(object sender, EventArgs e)
{
objState = EntityState.Added;
pContainer.Enabled = true;
registeredBindingSource.Add(new Registered());
registeredBindingSource.MoveLast();
txtregno.Focus();
}
This is the code for the save button:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
registeredBindingSource.EndEdit();
Registered obj = registeredBindingSource.Current as Registered;
if (obj != null)
{
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
if (db.State == ConnectionState.Closed)
db.Open();
if (objState == EntityState.Added)
{
DynamicParameters p = new DynamicParameters();
p.Add("#StudentID", dbType: DbType.Int32, direction: ParameterDirection.Output);
p.AddDynamicParams(new {
FullName = txtfullname.Text,
RegNo = txtregno.Text,
CourseTitle = obj.CourseTitle,
CourseStatus = obj.CourseStatus,
CourseUnit = obj.CourseUnit,
Department = txtdepartment.Text,
CurrentSemester = obj.CurrentSemester,
CurrentSession = obj.CurrentSession,
ModeOfStudy = txtmodeofstudy.Text,
Level = obj.Level,
ProgrammeOfStudy = txtprogramme.Text,
Faculty = txtfaculty.Text, finalSemester = obj.finalSemester
});
db.Execute("sp_StudentRegisteredCourse_insert", p, commandType: CommandType.StoredProcedure);
obj.StudentID = p.Get<int>("#StudentID");
}
else
{
db.Execute("sp_StudentRegisteredCourse_update", new { StudentID = obj.StudentID,FullName = txtfullname.Text,RegNo = txtregno.Text, CourseTitle = obj.CourseTitle,CourseStatus = obj.CourseStatus, CourseUnit = obj.CourseUnit, Department = txtdepartment.Text, CurrentSemester = obj.CurrentSemester,CurrentSession = obj.CurrentSession, ModeOfStudy = txtmodeofstudy.Text, Level = obj.Level, ProgrammeOfStudy = txtprogramme.Text,Faculty = txtfaculty.Text, finalSemester = obj.finalSemester },commandType:CommandType.StoredProcedure);
}
gridContainer.Refresh();
pContainer.Enabled = false;
objState = EntityState.unchanged;
}
}
}
catch (Exception ex)
{
MetroFramework.MetroMessageBox.Show(this, ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

How to show search results with their url's in Umbraco 7

I have implemented search in Umbraco 7 using examine and user control. Search is working fine. Now I need to show the URL of the search results displayed on the lists. Is there any index property like "BodyText" which can show the URL or do I have to do some stuff in user control?
User Control code:
public static class SiteSearchResultExtensions
{
public static string FullURL(this Examine.SearchResult sr)
{
return umbraco.library.NiceUrl(sr.Id);
}
}
public partial class SiteSearchResults : System.Web.UI.UserControl
{
#region Properties
private int _pageSize = 5;
public string PageSize
{
get { return _pageSize.ToString(); }
set
{
int pageSize;
if (int.TryParse(value, out pageSize))
{
_pageSize = pageSize;
}
else
{
_pageSize = 10;
}
}
}
private string SearchTerm
{
get
{
object o = this.ViewState["SearchTerm"];
if (o == null)
return "";
else
return o.ToString();
}
set
{
this.ViewState["SearchTerm"] = value;
}
}
protected IEnumerable<Examine.SearchResult> SearchResults
{
get;
private set;
}
#endregion
#region Events
protected override void OnLoad(EventArgs e)
{
try
{
CustomValidator.ErrorMessage = "";
if (!Page.IsPostBack)
{
topDataPager.PageSize = _pageSize;
bottomDataPager.PageSize = _pageSize;
string terms = Request.QueryString["s"];
if (!string.IsNullOrEmpty(terms))
{
SearchTerm = terms;
PerformSearch(terms);
}
}
base.OnLoad(e);
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
protected void searchResultsListView_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
try
{
if (SearchTerm != "")
{
topDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
bottomDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
PerformSearch(SearchTerm);
}
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
#endregion
#region Methods
private void PerformSearch(string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm)) return;
var criteria = ExamineManager.Instance
.SearchProviderCollection["ExternalSearcher"]
.CreateSearchCriteria(UmbracoExamine.IndexTypes.Content);
// Find pages that contain our search text in either their nodeName or bodyText fields...
// but exclude any pages that have been hidden.
//var filter = criteria
// .GroupedOr(new string[] { "nodeName", "bodyText" }, searchTerm)
// .Not()
// .Field("umbracoNaviHide", "1")
// .Compile();
Examine.SearchCriteria.IBooleanOperation filter = null;
var searchKeywords = searchTerm.Split(' ');
int i = 0;
for (i = 0; i < searchKeywords.Length; i++)
{
if (filter == null)
{
filter = criteria.GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
else
{
filter = filter.Or().GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
}
//SearchResults = ExamineManager.Instance
// .SearchProviderCollection["ExternalSearcher"]
// .Search(filter);
SearchResults = ExamineManager.Instance.SearchProviderCollection["ExternalSearcher"].Search(filter.Compile());
if (SearchResults.Count() > 0)
{
searchResultsListView.DataSource = SearchResults.ToArray();
searchResultsListView.DataBind();
searchResultsListView.Visible = true;
bottomDataPager.Visible = topDataPager.Visible = (SearchResults.Count() > _pageSize);
}
summaryLiteral.Text = "<p>Your search for <b>" + searchTerm + "</b> returned <b>" + SearchResults.Count().ToString() + "</b> result(s)</p>";
// Output the query which an be useful for debugging.
queryLiteral.Text = criteria.ToString();
}
#endregion
}
}
I have done my Examine settings like this:
ExamineIndex.Config
<IndexSet SetName="ExternalndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/ExternalIndex/">
<IndexAttributeFields>
<add Name="id"/>
<add Name="nodeName"/>
<add Name="nodeTypeAlias"/>
<add Name="parentID" />
</IndexAttributeFields>
<IndexUserFields>
<add Name="bodyText"/>
<add Name="umbracoNaviHide"/>
</IndexUserFields>
<IncludeNodeTypes/>
<ExcludeNodeTypes/>
</IndexSet>
ExamineSettings.Config
ExamineIndexProviders
<add name="ExternalIndexer" type="UmbracoExamine.UmbracoContentIndexer, UmbracoExamine"
runAsync="true"
supportUnpublished="true"
supportProtected="true"
interval="10"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>
ExamineSearchProvide
<add name="ExternalSearcher" type="UmbracoExamine.UmbracoExamineSearcher, UmbracoExamine"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>
It was quite simple and i done some editing in the Usercontrol(SiteSearchresult.ascx)
like this
<li>
<a href="<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>">
<%# ((Examine.SearchResult)Container.DataItem).Fields["nodeName"] %>
<br >
addingvalue.webdevstaging.co.uk<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>
</a>
<p><%# ((Examine.SearchResult)Container.DataItem).Fields.ContainsKey("bodyText") == true ? ((Examine.SearchResult)Container.DataItem).Fields["bodyText"] : ""%></p>
</li>

Telerik RadGrid Export to Excel. Missing operand before '=' operator

I am getting the error
Missing operand before '=' operator.
when I try and export and the code is running fine in the grid.
Here is the code for the web part. The error only occurs on the rebind. It works fine in the grid itself. Is there any way to narrow down the exact thing it is erroring on?
I am willing to pay for a support / solution to this problem, I just need it to work.
[Guid("5fbe4ccf-4d90-476b-af77-347de4e1176c")]
public class ParentChildGrid : Microsoft.SharePoint.WebPartPages.WebPart
{
#region
Variables
private bool _error = false;
private string _PageSize = null;
private string _ParentList = null;
private string _ParentView = null;
private string _ParentIDField = null;
private string _FirstChildList = null;
private string _FirstChildView = null;
private string _FirstChildIDField = null;
private string _FirstChildParentIDField = null;
private string _SecondChildList = null;
private string _SecondChildView = null;
private string _SecondChildIDField = null;
private string _SecondChildParentIDField = null;
protected ScriptManager scriptManager;
protected RadAjaxManager ajaxManager;
protected Panel panel;
protected SPView oView;
protected RadGrid oGrid = new RadGrid();
protected Label label;
protected DataTable ParentDataTable;
protected DataTable Child1DataTable;
protected DataTable Child2DataTable;
protected Button cmdExport = new Button();
#endregion
#region
Properties
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("Items Per Page")]
[WebDescription("# of items to include in each page.")]
public string PageSize
{
get
{
if (_PageSize == null)
{
_PageSize = "100";
}
return _PageSize.Trim();
}
set { _ParentList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("ParentList")]
[WebDescription("Parent List in Grid View")]
public string ParentList
{
get
{
if (_ParentList == null)
{
_ParentList = "";
}
return _ParentList.Trim();
}
set { _ParentList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("ParentView")]
[WebDescription("View for Parent List")]
public string ParentView
{
get
{
if (_ParentView == null)
{
_ParentView = "";
}
return _ParentView.Trim();
}
set { _ParentView = value.Trim(); }
}
[
Personalizable(PersonalizationScope.Shared)]
[
WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[
WebDisplayName("ParentIDField")]
[
WebDescription("ID Field in Parent List")]
public string ParentIDField
{
get
{
if (_ParentIDField == null)
{
_ParentIDField = "";
}
return _ParentIDField.Trim();
}
set { _ParentIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("FirstChildList")]
[WebDescription("FirstChildList Name")]
public string FirstChildList
{
get
{
if (_FirstChildList == null)
{
_FirstChildList = "";
}
return _FirstChildList.Trim();
}
set { _FirstChildList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildView")]
[WebDescription("First Child View Name")]
public string FirstChildView
{
get
{
if (_FirstChildView == null)
{
_FirstChildView = "";
}
return _FirstChildView.Trim();
}
set { _FirstChildView = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildIDField")]
[WebDescription("First Child ID Field (Tyically ID)")]
public string FirstChildIDField
{
get
{
if (_FirstChildIDField == null)
{
_FirstChildIDField = "";
}
return _FirstChildIDField.Trim();
}
set { _FirstChildIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildParentIDField")]
[WebDescription("First Child Parent ID Field")]
public string FirstChildParentIDField
{
get
{
if (_FirstChildParentIDField == null)
{
_FirstChildParentIDField = "";
}
return _FirstChildParentIDField.Trim();
}
set { _FirstChildParentIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildList")]
[WebDescription("Second Child List")]
public string SecondChildList
{
get
{
if (_SecondChildList == null)
{
_SecondChildList = "";
}
return _SecondChildList.Trim();
}
set { _SecondChildList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildView")]
[
WebDescription("Second Child View")]
public string SecondChildView
{
get
{
if (_SecondChildView == null)
{
_SecondChildView = "";
}
return _SecondChildView.Trim();
}
set { _SecondChildView = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildIDField")]
[WebDescription("Second Child ID Field (Typically ID)")]
public string SecondChildIDField
{
get
{
if (_SecondChildIDField == null)
{
_SecondChildIDField = "";
}
return _SecondChildIDField.Trim();
}
set { _SecondChildIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("SecondChildParentIDField")]
[WebDescription("Second Child ID Field")]
public string SecondChildParentIDField
{
get
{
if (_SecondChildParentIDField == null)
{
_SecondChildParentIDField = "";
}
return _SecondChildParentIDField.Trim();
}
set { _SecondChildParentIDField = value.Trim(); }
}
#endregion
private const string ByeByeIncludeScriptKey = "myByeByeIncludeScript";
private const string EmbeddedScriptFormat = "<script language=javascript>function ByeBye(){ alert('Test Code'); }</script> ";
private const string DisableAjaxScriptKey = "myDisableAjaxIncludeScript";
private const string DisableAjaxForExport = "<script language=javascript>function onRequestStart(sender, args) { if (args.get_eventTarget().indexOf(\"cmdExport\") >= 0);args.set_enableAjax(false);alert('Ajax Disabled'); }</script>";
private void WebPart_ClientScript_PreRender(object sender , System.EventArgs e )
{
if (!Page.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey))
Page.RegisterClientScriptBlock(ByeByeIncludeScriptKey,
EmbeddedScriptFormat);
if (!Page.IsClientScriptBlockRegistered(DisableAjaxScriptKey))
Page.RegisterClientScriptBlock(DisableAjaxScriptKey,
DisableAjaxForExport);
//ajaxManager.ClientEvents.OnRequestStart = "onRequestStart";
}
public ParentChildGrid()
{
this.ExportMode = WebPartExportMode.All;
this.PreRender += new EventHandler(WebPart_ClientScript_PreRender);
}
private void onRequestStart()
{
ajaxManager.EnableAJAX =
false;
}
protected override void OnInit(EventArgs e)
{
try
{
base.OnInit(e);
Page.ClientScript.RegisterStartupScript(
typeof(ParentChildGrid), this.ID, "_spOriginalFormAction = document.forms[0].action;_spSuppressFormOnSubmitWrapper=true;", true);
if (this.Page.Form != null)
{
string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
if (!string.IsNullOrEmpty(formOnSubmitAtt) && formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
{
this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
}
}
scriptManager =
ScriptManager.GetCurrent(this.Page);
if (scriptManager == null)
{
scriptManager =
new RadScriptManager();
this.Page.Form.Controls.AddAt(0, scriptManager);
}
scriptManager.RegisterPostBackControl(cmdExport);
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void OnLoad(EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdExport);
if (!_error)
{
try
{
base.OnLoad(e);
this.EnsureChildControls();
base.OnLoad(e);
if (_ParentList != null)
{
if (_ParentList != "")
{
panel =
new Panel();
panel.ID =
"Panel1";
this.Controls.Add(panel);
oGrid =
new RadGrid();
DefineComplexGrid();
oGrid.GridExporting +=
new OnGridExportingEventHandler(oGrid_GridExporting);
panel.Controls.Add(oGrid);
//DefineSimpleMasterDetail();
cmdExport.Click +=
new EventHandler(cmdExport_Click);
cmdExport.Text =
"Export";
Button cmdExpandAll = new Button();
cmdExpandAll.Text =
"Expand All";
cmdExpandAll.Click +=
new EventHandler(cmdExpandAll_Click);
panel.Controls.Add(cmdExpandAll);
ajaxManager =
RadAjaxManager.GetCurrent(this.Page);
if (ajaxManager == null)
{
ajaxManager =
new RadAjaxManager();
ajaxManager.ID =
"RadAjaxManager1";
Controls.Add(ajaxManager);
this.Page.Items.Add(typeof(RadAjaxManager), ajaxManager);
}
ajaxManager.AjaxSettings.AddAjaxSetting(oGrid, panel);
panel.Controls.Add(cmdExport);
ajaxManager.AjaxRequest +=
new RadAjaxControl.AjaxRequestDelegate(ajaxManager_AjaxRequest);
this.Controls.Add(new LiteralControl("<br><br><input class='ms-SPButton' value=\'Test Code\' type=button onclick=\"ByeBye();\" >"));
ajaxManager.ClientEvents.OnRequestStart =
"onRequestStart";
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
}
void oGrid_GridExporting(object source, GridExportingArgs e)
{
//throw new NotImplementedException();
}
void ajaxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
ajaxManager.EnableAJAX =
false;
}
void cmdExpandAll_Click(object sender, EventArgs e)
{
try
{
foreach (GridItem item in oGrid.MasterTableView.Items)
{
item.Expanded =
true;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
void cmdExport_Click(object sender, EventArgs e)
{
try
{
ajaxManager.ClientEvents.OnRequestStart =
"onRequestStart";
oGrid.ExportSettings.ExportOnlyData =
true;
oGrid.ExportSettings.IgnorePaging =
true;
oGrid.ExportSettings.OpenInNewWindow =
true;
oGrid.MasterTableView.HierarchyDefaultExpanded =
true;
if (FirstChildList.Trim() != "")
oGrid.MasterTableView.DetailTables[0].HierarchyDefaultExpanded =
true;
if (SecondChildList.Trim() != "")
oGrid.MasterTableView.DetailTables[1].HierarchyDefaultExpanded =
true;
oGrid.Rebind();
oGrid.MasterTableView.ExportToExcel();
}
catch (Exception ex)
{
HandleException(ex);
}
}
//private void DefineSimpleGrid()
//{
// try
// {
// oGrid.ID = "Master";
// oGrid.PageSize = 10;
// oGrid.AllowPaging = true;
// oGrid.AllowSorting = true;
// oGrid.Skin = "WebBlue";
// oGrid.GroupingEnabled = true;
// oGrid.NeedDataSource += new GridNeedDataSourceEventHandler(oGrid_NeedDataSource);
// oGrid.ShowStatusBar = true;
// oGrid.ShowGroupPanel = true;
// oGrid.GroupingEnabled = true;
// oGrid.ClientSettings.AllowDragToGroup = true;
// oGrid.ClientSettings.AllowColumnsReorder = true;
// }
// catch (Exception ex)
// {
// HandleException(ex);
// }
//}
private DataTable GetDataTable(String cListName, String ViewName)
{
try
{
SPList list = SPContext.Current.Web.Lists[cListName];
SPView view = list.Views[ViewName];
SPListItemCollection items = list.GetItems(view);
if (items != null)
{
if (items.Count > 0)
return items.GetDataTable();
}
}
catch (Exception ex)
{
HandleException(ex);
}
return null;
}
//private void DefineSimpleMasterDetail()
//{
// try
// {
// oGrid.MasterTableView.DataKeyNames = new string[] { "ID" };
// oGrid.Skin = "Default";
// oGrid.Width = Unit.Percentage(100);
// oGrid.PageSize = 5;
// oGrid.AllowPaging = true;
// oGrid.MasterTableView.PageSize = 15;
// oGrid.MasterTableView.DataSource = GetDataTable(_ParentList, _ParentView);
// GridTableView tableViewOrders = new GridTableView(oGrid);
// tableViewOrders.DataSource = GetDataTable(_FirstChildList, _FirstChildView);
// tableViewOrders.DataKeyNames = new string[] { _ParentIDField };
// GridRelationFields relationFields = new GridRelationFields();
// relationFields.MasterKeyField = _FirstChildIDField;
// relationFields.DetailKeyField = _FirstChildParentIDField;
// tableViewOrders.ParentTableRelation.Add(relationFields);
// oGrid.MasterTableView.DetailTables.Add(tableViewOrders);
// }
// catch (Exception ex)
// {
// HandleException(ex);
// }
//}
private void DefineComplexGrid()
{
try
{
oGrid.ID =
"RadGrid1";
//oGrid.Width = Unit.Percentage(98);
oGrid.PageSize =
Convert.ToInt32(PageSize);
oGrid.AllowPaging =
true;
oGrid.AllowSorting =
true;
oGrid.PagerStyle.Mode =
GridPagerMode.NextPrevAndNumeric;
oGrid.ShowStatusBar =
true;
oGrid.ClientSettings.Resizing.AllowColumnResize =
true;
oGrid.DetailTableDataBind +=
new GridDetailTableDataBindEventHandler(oGrid_DetailTableDataBind);
oGrid.NeedDataSource +=
new GridNeedDataSourceEventHandler(oGrid_NeedDataSource);
oGrid.ColumnCreated +=
new GridColumnCreatedEventHandler(oGrid_ColumnCreated);
oGrid.MasterTableView.Name = _ParentList;
if (_FirstChildList != "" || _SecondChildList != "")
{
oGrid.MasterTableView.PageSize =
Convert.ToInt32(PageSize);
oGrid.MasterTableView.DataKeyNames =
new string[] { _ParentIDField };
oGrid.MasterTableView.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
}
if (_FirstChildList != "")
{
GridTableView tableViewFirstChild = new GridTableView(oGrid);
tableViewFirstChild.Width =
Unit.Percentage(100);
tableViewFirstChild.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
tableViewFirstChild.DataKeyNames =
new string[] { _FirstChildIDField };
tableViewFirstChild.Name = _FirstChildList;
GridRelationFields FirstChildrelationFields = new GridRelationFields();
FirstChildrelationFields.MasterKeyField = _ParentIDField;
FirstChildrelationFields.DetailKeyField = _FirstChildParentIDField;
tableViewFirstChild.ParentTableRelation.Add(FirstChildrelationFields);
tableViewFirstChild.Caption = _FirstChildList;
oGrid.MasterTableView.DetailTables.Add(tableViewFirstChild);
}
if (_SecondChildList != "")
{
GridTableView tableViewSecondChild = new GridTableView(oGrid);
tableViewSecondChild.Width =
Unit.Percentage(100);
tableViewSecondChild.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
tableViewSecondChild.DataKeyNames =
new string[] { _SecondChildIDField };
tableViewSecondChild.Name = _SecondChildList;
GridRelationFields SecondChildrelationFields = new GridRelationFields();
SecondChildrelationFields.MasterKeyField = _ParentIDField;
SecondChildrelationFields.DetailKeyField = _SecondChildParentIDField;
tableViewSecondChild.Caption = _SecondChildList;
tableViewSecondChild.ParentTableRelation.Add(SecondChildrelationFields);
oGrid.MasterTableView.DetailTables.Add(tableViewSecondChild);
}
oGrid.ShowStatusBar =
true;
oGrid.ShowGroupPanel =
true;
oGrid.GroupingEnabled =
true;
oGrid.ClientSettings.AllowDragToGroup =
true;
oGrid.ClientSettings.AllowColumnsReorder =
true;
oGrid.Skin =
"Web20";
}
catch (Exception ex)
{
HandleException(ex);
}
}
void oGrid_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
{
try
{
//if (e.Column.HeaderText == "ID" || e.Column.HeaderText == "Created")
//{
// e.Column.Display = false;
// return;
//}
String cOwnerTable = "";
cOwnerTable = e.OwnerTableView.Name;
if (cOwnerTable.Trim() != "" && e.Column.HeaderText != "" && e.Column.HeaderText != _FirstChildParentIDField && e.Column.HeaderText != _SecondChildParentIDField)
{
SPList CurrentList = SPContext.Current.Web.Lists[e.OwnerTableView.Name];
e.Column.HeaderText = GetFieldDisplayName(e.Column.HeaderText, CurrentList);
SPField oField = CurrentList.Fields[e.Column.HeaderText];
GridBoundColumn col = (GridBoundColumn)e.Column;
switch (oField.Type)
{
case SPFieldType.Currency:
col.DataFormatString =
"{0:C}";
break;
case SPFieldType.DateTime:
SPFieldDateTime oDateTime = (SPFieldDateTime)oField;
if (oDateTime.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
col.DataFormatString =
"{0:d}";
break;
default:
break;
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private DataTable GetChildDataTable(GridDetailTableDataBindEventArgs e, String cChildListName, String cChildView,String cParentIDField)
{
try
{
GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem;
SPList FirstChildList = SPContext.Current.Web.Lists[cChildListName];
SPView oView = FirstChildList.Views[cChildView];
String cContractID = parentItem[_ParentIDField].Text;
SPQuery oChildQuery = new SPQuery();
if (Occurs(cParentIDField, oView.Query) == 2)
{
String cNewQuery = oView.Query;
Int32 iPos = cNewQuery.IndexOf(cParentIDField) + cParentIDField.Length;
String cPartOne = cNewQuery.Substring(0,cNewQuery.IndexOf(cParentIDField, iPos));
String cPartTwo = cNewQuery.Substring(cNewQuery.IndexOf(cParentIDField, iPos) + cParentIDField.Length);
cNewQuery = cPartOne + cContractID + cPartTwo;
oChildQuery.Query = cNewQuery;
oChildQuery.Query =
"<Where><Eq><FieldRef Name='" + cParentIDField + "' /><Value Type='Text'>" + cContractID + "</Value></Eq></Where>";
}
else
{
oChildQuery.Query =
"<Where><Eq><FieldRef Name='" + cParentIDField + "' /><Value Type='Text'>" + cContractID + "</Value></Eq></Where>";
}
SPViewFieldCollection oViewFields = oView.ViewFields;
oViewFields.Add(cParentIDField);
String cViewFields = oViewFields.SchemaXml;
oChildQuery.ViewFields = cViewFields;
SPListItemCollection items = FirstChildList.GetItems(oChildQuery);
if (items != null)
{
if (items.Count > 0)
{
return items.GetDataTable();
}
}
}
catch (Exception ex)
{
//HandleException(ex);
}
return null;
}
void oGrid_DetailTableDataBind(object source, GridDetailTableDataBindEventArgs e)
{
try
{
GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem;
if (parentItem.Edit)
{
return;
}
if (e.DetailTableView.Name == _FirstChildList)
{
Child1DataTable = GetChildDataTable(e, _FirstChildList, _FirstChildView, _FirstChildParentIDField);
e.DetailTableView.DataSource = Child1DataTable;
}
if (e.DetailTableView.Name == _SecondChildList)
{
Child2DataTable = GetChildDataTable(e, _SecondChildList, _SecondChildView, _SecondChildParentIDField);
e.DetailTableView.DataSource = Child2DataTable;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
void oGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
if (!e.IsFromDetailTable)
{
SPList ParentList = SPContext.Current.Web.Lists[_ParentList];
oView = ParentList.Views[_ParentView];
SPQuery ParentQuery = new SPQuery();
ParentQuery.Query = oView.Query;
ParentQuery.RowLimit = 100000;
ParentQuery.ViewFields = oView.ViewFields.SchemaXml;
SPListItemCollection oItems = SPContext.Current.Web.Lists[_ParentList].GetItems(ParentQuery);
ParentDataTable = oItems.GetDataTable();
oGrid.DataSource = ParentDataTable;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private string GetFieldDisplayName(String cInternalName, SPList oList)
{
try
{
foreach (SPField field in oList.Fields)
{
if (field.InternalName == cInternalName)
return field.Title;
}
}
catch (Exception ex)
{
HandleException(ex);
}
return cInternalName;
}
private Int32 Occurs(String SearchFor, String SearchIn)
{
Int32 Count = 0;
Int32 iPos = 0;
try
{
while (SearchIn.IndexOf(SearchFor, iPos) != -1)
{
Count++;
iPos = SearchIn.IndexOf(SearchFor, iPos) + 1;
}
}
catch (Exception ex)
{
HandleException(ex);
}
return Count;
}
private void HandleException(Exception ex)
{
this._error = true;
try
{
this.Controls.Clear();
this.Controls.Add(new LiteralControl(ex.Message));
}
catch
{
}
}
} //End Class
As a follow-up, it appears the problem was that there were NULL values in John's original data. These nulls were causing problems during the data export. Fixing the null values also fixed the Excel export. Original solution on Telerik.com forums:
http://www.telerik.com/community/forums/aspnet-ajax/grid/extremely-frustrated-please-help-with-radgrid-export-of-multi-tabe-view.aspx

Resources