Get posted file over HTTP Listener in c# - c#-4.0

I have make a simple http server using c#. And I know how to get posted data and output them. Here is my c# code
public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:8080").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
showPostedData(con.Request);
con.Response.StatusCode = (int)HttpStatusCode.NotFound;
string data = "Uploaded successful";
byte[] output = Encoding.ASCII.GetBytes(data);
con.Response.ContentType = "text/html";
con.Response.ContentLength64 = output.Length;
con.Response.OutputStream.Write(output , 0, output.Length );
}
}
public static void showPostedData(HttpListenerRequest request){
if (!request.HasEntityBody)
{
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string text;
if (request.ContentType != null)
{
text = reader.ReadToEnd();
}
Console.WriteLine( text );
}
My client html form has input box named file: <input type="file" name"file">
In the console output is like that :
file='Path of Choosed file not a file'
So How i get POSTED files and copy them to upload directory..?
Sorry for my english and thanks in advance...

public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:80").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
var values = new HttpNameValueCollection(ref con);
try
{
Console.WriteLine(values.Files["file"].FileName);
File.WriteAllText(values.Files["file"].FileName, values.Files["file"].FileData, Encoding.Default);
}
catch (Exception tr)
{
}
}
}
class HTTPFormData
{
public class File
{
private string _fileName;
public string FileName { get { return _fileName ?? (_fileName = ""); } set { _fileName = value; } }
private string _fileData;
public string FileData { get { return _fileData ?? (_fileName = ""); } set { _fileData = value; } }
private string _contentType;
public string ContentType { get { return _contentType ?? (_contentType = ""); } set { _contentType = value; } }
}
private NameValueCollection _post;
private Dictionary<string, File> _files;
private readonly HttpListenerContext _ctx;
public NameValueCollection Post { get { return _post ?? (_post = new NameValueCollection()); } set { _post = value; } }
public NameValueCollection Get { get { return _ctx.Request.QueryString; } }
public Dictionary<string, File> Files { get { return _files ?? (_files = new Dictionary<string, File>()); } set { _files = value; } }
private void PopulatePostMultiPart(string post_string)
{
var boundary_index = _ctx.Request.ContentType.IndexOf("boundary=") + 9;
var boundary = _ctx.Request.ContentType.Substring(boundary_index, _ctx.Request.ContentType.Length - boundary_index);
var upper_bound = post_string.Length - 4;
if (post_string.Substring(2, boundary.Length) != boundary)
throw (new InvalidDataException());
var current_string = new StringBuilder();
for (var x = 4 + boundary.Length; x < upper_bound; ++x)
{
if (post_string.Substring(x, boundary.Length) == boundary)
{
x += boundary.Length + 1;
var post_variable_string = current_string.Remove(current_string.Length - 4, 4).ToString();
var end_of_header = post_variable_string.IndexOf("\r\n\r\n");
if (end_of_header == -1) throw (new InvalidDataException());
var filename_index = post_variable_string.IndexOf("filename=\"", 0, end_of_header);
var filename_starts = filename_index + 10;
var content_type_starts = post_variable_string.IndexOf("Content-Type: ", 0, end_of_header) + 14;
var name_starts = post_variable_string.IndexOf("name=\"") + 6;
var data_starts = end_of_header + 4;
if (filename_index != -1)
{
var filename = post_variable_string.Substring(filename_starts, post_variable_string.IndexOf("\"", filename_starts) - filename_starts);
var content_type = post_variable_string.Substring(content_type_starts, post_variable_string.IndexOf("\r\n", content_type_starts) - content_type_starts);
var file_data = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
Files.Add(name, new File() { FileName = filename, ContentType = content_type, FileData = file_data });
}
else
{
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
var value = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
Post.Add(name, value);
}
current_string.Clear();
continue;
}
current_string.Append(post_string[x]);
}
}
private void PopulatePost()
{
if (_ctx.Request.HttpMethod != "POST" || _ctx.Request.ContentType == null) return;
var post_string = new StreamReader(_ctx.Request.InputStream, _ctx.Request.ContentEncoding).ReadToEnd();
if (_ctx.Request.ContentType.StartsWith("multipart/form-data"))
PopulatePostMultiPart(post_string);
}
public HTTPFormData(ref HttpListenerContext ctx)
{
_ctx = ctx;
PopulatePost();
}
}

Related

XPages: How to acces an application scope bean from a session scope bean

I need a value from my application scope managed bean in my session scope managed bean. Not sure how to get this done. Saw a poste here: https://guedebyte.wordpress.com/2012/05/19/accessing-beans-from-java-code-in-xpages-learned-by-reading-the-sourcecode-of-the-extensionlibrary/ But I get a bunch of errors... I also found this: JSF 2.0 Accessing Application Scope bean from another Bean so IM thinking maybe I need to redefine my application bean??? Totally clueless...
How can I make that happen?
Here is the application scope bean's code:
public class AppConfig implements Serializable {
private static final long serialVersionUID = 2768250939591274442L;
public AppConfig() {
initDefaults();
initFromConfigDoc();
}
// Control the number of entries displayed in the widgets
private int nbWidgetFavorites = 0;
private int nbWidgetMostPopular = 0;
private int nbWidgetToolbox = 0;
// Control the number of entries to display in the What's new view
private int nbWhatsNew = 0;
private String showDetailsWhatsNew = "no";
//controls various search options
private int nbSearchResults = 0;
private int nbMaxSearchResults = 0;
//the home page to use for each language
private String homePageUNID_FR = "";
private String homePageUNID_EN = "";
//application email address to use (webmaster)
// DEV ADDRESS
private String appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
// UAT ADDRESS
// PROD ADDRESS
//path to the stats DB
private String statsDB = "";
//application message, if needed
private String systemMessageFR = "";
private String systemMessageEN = "";
//default lang (defined here as session bean will read from the App bean first to
// see if there's a value stored there)
private String defaultLang = "";
//default prov
private String defaultProv = "";
// show Province drop down?
private String showProv = "no";
//various text for "share this link" emails
private String senderEmail = "";
private String senderName = "";
private String appURL = "";
private String emailText = "";
private String clickLinkText = "";
private String emailFooter = "";
private String messageIntro = "";
private String allowRatingModification = "";
/*****************************************************************************/
private void initDefaults() {
// Control the number of entries displayed in the widgets
nbWidgetFavorites = 10;
nbWidgetMostPopular = 10;
nbWidgetToolbox = 10;
nbWhatsNew = 15;
showDetailsWhatsNew = "no";
nbSearchResults = 25;
nbMaxSearchResults = 100;
homePageUNID_FR = "";
homePageUNID_EN = "";
appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
statsDB = "belair\\xBiblioStats.nsf";
systemMessageFR = "";
systemMessageEN = "";
defaultLang = "FR";
defaultProv = "QC";
showProv = "no";
allowRatingModification = "1";
}
/*****************************************************************************/
public boolean persistToConfigDoc() {
//write content of sessionScope vars to config doc
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc == null) {
doc = db.createDocument();
doc.replaceItemValue("form", "AppConfig");
}
doc.replaceItemValue("nbWidgetFavorites", this.nbWidgetFavorites);
doc.replaceItemValue("nbWidgetMostPopular", this.nbWidgetMostPopular);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWhatsNew", this.nbWhatsNew);
doc.replaceItemValue("showDetailsWhatsNew", this.showDetailsWhatsNew);
doc.replaceItemValue("nbSearchResults", this.nbSearchResults);
doc.replaceItemValue("nbMaxSearchResults", this.nbMaxSearchResults);
doc.replaceItemValue("homePageUNID_FR", this.homePageUNID_FR);
doc.replaceItemValue("homePageUNID_EN", this.homePageUNID_EN);
doc.replaceItemValue("appEmailAddress", this.appEmailAddress);
doc.replaceItemValue("statsDB", this.statsDB);
doc.replaceItemValue("systemMessageFR", this.systemMessageFR);
doc.replaceItemValue("systemMessageEN", this.systemMessageEN);
doc.replaceItemValue("defaultLang", this.defaultLang);
doc.replaceItemValue("defaultProv", this.defaultProv);
doc.replaceItemValue("showProv", this.showProv);
doc.replaceItemValue("senderEmail", this.senderEmail);
doc.replaceItemValue("senderName", this.senderName);
doc.replaceItemValue("appURL", this.appURL);
doc.replaceItemValue("emailText", this.emailText);
doc.replaceItemValue("clickLinkText", this.clickLinkText);
doc.replaceItemValue("emailFooter", this.emailFooter);
doc.replaceItemValue("messageIntro", this.messageIntro);
doc.replaceItemValue("allowRatingModification", this.allowRatingModification);
doc.save();
return true;
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/*****************************************************************************/
public void initFromConfigDoc() {
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc != null) {
//load default values
if(doc.hasItem("nbWidgetFavorites")) {
int tmp = doc.getItemValueInteger("nbWidgetFavorites");
if(tmp > 0) {
this.nbWidgetFavorites = tmp;
}
}
if(doc.hasItem("nbWidgetMostPopular")) {
int tmp = doc.getItemValueInteger("nbWidgetMostPopular");
if(tmp > 0) {
this.nbWidgetMostPopular = tmp;
}
}
if(doc.hasItem("nbWidgetToolbox")) {
int tmp = doc.getItemValueInteger("nbWidgetToolbox");
if(tmp > 0) {
this.nbWidgetToolbox = tmp;
}
}
if(doc.hasItem("nbWhatsNew")) {
int tmp = doc.getItemValueInteger("nbWhatsNew");
if(tmp > 0) {
this.nbWhatsNew = tmp;
}
}
if(doc.hasItem("showDetailsWhatsNew")) {
String tmp = doc.getItemValueString("showDetailsWhatsNew");
this.showDetailsWhatsNew = tmp;
}
if(doc.hasItem("nbSearchResults")) {
int tmp = doc.getItemValueInteger("nbSearchResults");
if(tmp > 0) {
this.nbSearchResults = tmp;
}
}
if(doc.hasItem("nbMaxSearchResults")) {
int tmp = doc.getItemValueInteger("nbMaxSearchResults");
if(tmp > 0) {
this.nbMaxSearchResults = tmp;
}
}
if(doc.hasItem("homePageUNID_FR")) {
String tmp = doc.getItemValueString("homePageUNID_FR");
if(!"".equals(tmp)) {
this.homePageUNID_FR = tmp;
}
}
if(doc.hasItem("homePageUNID_EN")) {
String tmp = doc.getItemValueString("homePageUNID_EN");
if(!"".equals(tmp)) {
this.homePageUNID_EN = tmp;
}
}
if(doc.hasItem("appEmailAddress")) {
String tmp = doc.getItemValueString("appEmailAddress");
if(!"".equals(tmp)) {
this.appEmailAddress = tmp;
}
}
if(doc.hasItem("statsDB")) {
String tmp = doc.getItemValueString("statsDB");
if(!"".equals(tmp)) {
this.statsDB = tmp;
}
}
if(doc.hasItem("systemMessageFR")) {
String tmp = doc.getItemValueString("systemMessageFR");
if(!"".equals(tmp)) {
this.systemMessageFR = tmp;
}
}
if(doc.hasItem("systemMessageEN")) {
String tmp = doc.getItemValueString("systemMessageEN");
if(!"".equals(tmp)) {
this.systemMessageEN = tmp;
}
}
if(doc.hasItem("defaultLang")) {
String tmp = doc.getItemValueString("defaultLang");
if(!"".equals(tmp)) {
this.defaultLang = tmp;
}
}
if(doc.hasItem("defaultProv")) {
String tmp = doc.getItemValueString("defaultProv");
if(!"".equals(tmp)) {
this.defaultProv = tmp;
}
}
if(doc.hasItem("showProv")) {
String tmp = doc.getItemValueString("showProv");
if(!"".equals(tmp)) {
this.showProv = tmp;
}
}
if(doc.hasItem("senderEmail")) {
String tmp = doc.getItemValueString("senderEmail");
if(!"".equals(tmp)) {
this.senderEmail = tmp;
}
}
if(doc.hasItem("senderName")) {
String tmp = doc.getItemValueString("senderName");
if(!"".equals(tmp)) {
this.senderName = tmp;
}
}
if(doc.hasItem("appURL")) {
String tmp = doc.getItemValueString("appURL");
if(!"".equals(tmp)) {
this.appURL = tmp;
}
}
if(doc.hasItem("emailText")) {
String tmp = doc.getItemValueString("emailText");
if(!"".equals(tmp)) {
this.emailText = tmp;
}
}
if(doc.hasItem("clickLinkText")) {
String tmp = doc.getItemValueString("clickLinkText");
if(!"".equals(tmp)) {
this.clickLinkText = tmp;
}
}
if(doc.hasItem("emailFooter")) {
String tmp = doc.getItemValueString("emailFooter");
if(!"".equals(tmp)) {
this.emailFooter = tmp;
}
}
if(doc.hasItem("messageIntro")) {
String tmp = doc.getItemValueString("messageIntro");
if(!"".equals(tmp)) {
this.messageIntro = tmp;
}
}
//allowRatingModification
if(doc.hasItem("allowRatingModification")) {
String tmp = doc.getItemValueString("allowRatingModification");
if(!"".equals(tmp)) {
this.allowRatingModification = tmp;
}
}
}
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*****************************************************************************/
public int getNbWidgetFavorites() {
return nbWidgetFavorites;
}
public void setNbWidgetFavorites(int nbWidgetFavorites) {
this.nbWidgetFavorites = nbWidgetFavorites;
}
public int getNbWidgetMostPopular() {
return nbWidgetMostPopular;
}
public void setNbWidgetMostPopular(int nbWidgetMostPopular) {
this.nbWidgetMostPopular = nbWidgetMostPopular;
}
public int getNbWidgetToolbox() {
return nbWidgetToolbox;
}
public void setNbWidgetToolbox(int nbWidgetToolbox) {
this.nbWidgetToolbox = nbWidgetToolbox;
}
public void setNbWhatsNew(int nbWhatsNew) {
this.nbWhatsNew = nbWhatsNew;
}
public int getNbWhatsNew() {
return nbWhatsNew;
}
public void setShowDetailsWhatsNew(String showDetailsWhatsNew) {
this.showDetailsWhatsNew = showDetailsWhatsNew;
}
public String getShowDetailsWhatsNew() {
return showDetailsWhatsNew;
}
public int getNbSearchResults() {
return nbSearchResults;
}
public void setNbSearchResults(int nbSearchResults) {
this.nbSearchResults = nbSearchResults;
}
public int getNbMaxSearchResults() {
return nbMaxSearchResults;
}
public void setNbMaxSearchResults(int nbMaxSearchResults) {
this.nbMaxSearchResults = nbMaxSearchResults;
}
public String getHomePageUNID_FR() {
return homePageUNID_FR;
}
public void setHomePageUNID_FR(String homePageUNID_FR) {
this.homePageUNID_FR = homePageUNID_FR;
}
public String getHomePageUNID_EN() {
return homePageUNID_EN;
}
public void setHomePageUNID_EN(String homePageUNID_EN) {
this.homePageUNID_EN = homePageUNID_EN;
}
public String getAppEmailAddress() {
return appEmailAddress;
}
public void setAppEmailAddress(String appEmailAddress) {
this.appEmailAddress = appEmailAddress;
}
public String getSystemMessageFR() {
return systemMessageFR;
}
public void setSystemMessageFR(String systemMessageFR) {
this.systemMessageFR = systemMessageFR;
}
public String getSystemMessageEN() {
return systemMessageEN;
}
public void setSystemMessageEN(String systemMessageEN) {
this.systemMessageEN = systemMessageEN;
}
public void setStatsDB(String statsDB) {
this.statsDB = statsDB;
}
public String getStatsDB() {
return statsDB;
}
public void setDefaultLang(String defaultLang) {
this.defaultLang = defaultLang;
}
public String getDefaultProv() {
return defaultProv;
}
public void setDefaultProv(String defaultPRov) {
this.defaultProv = defaultPRov;
}
public void setShowProv(String showProv) {
this.showProv = showProv;
}
public String getShowProv() {
return showProv;
}
public String getDefaultLang() {
return defaultLang;
}
public String getMessageIntro() {
return messageIntro;
}
public void setMessageIntro(String messageIntro) {
this.messageIntro = messageIntro;
}
public String getSenderEmail() {
return senderEmail;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getAppURL() {
return appURL;
}
public void setAppURL(String appURL) {
this.appURL = appURL;
}
public String getEmailText() {
return emailText;
}
public void setEmailText(String emailText) {
this.emailText = emailText;
}
public String getClickLinkText() {
return clickLinkText;
}
public void setClickLinkText(String clickLinkText) {
this.clickLinkText = clickLinkText;
}
public String getEmailFooter() {
return emailFooter;
}
public void setEmailFooter(String emailFooter) {
this.emailFooter = emailFooter;
}
//allowRatingModification
public String getAllowRatingModification() {
return allowRatingModification;
}
public void setAllowRatingModification(String allowRatingModification) {
this.allowRatingModification = allowRatingModification;
}
}
The VariableResolver goes through all implicit variables (e.g. session, database) as well as scoped variables (e.g. applicationScope.myVar). Your bean is also accessed from SSJS via the VariableResolver.
So you can use:
ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "myAppScopeBean");
This is not a direct answer to your question...
An alternative would be to set the value you want in applicationScope and then access it this way from your bean. To access the entire bean directly is a different answer.
You use this code get a handle to your applicationScope.
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
Map<String, Object> applicationScope = externalContext.getApplicationMap();
Then to use this you have code like this:
String agentLogDB = (String) applicationScope.get("LOGDB");

how to upload audio to server: Blackberry

I'm trying to upload an .amr file to the server. My Code as follows:
private static void uploadRecording(byte[] data) {
byte[] response=null;
String currentFile = getFileName(); //the .amr file to upload
StringBuffer connectionStr=new StringBuffer("http://www.myserver/bb/upload.php");
connectionStr.append(getString());
PostFile req;
try {
req = new PostFile(connectionStr.toString(),
"uploadedfile", currentFile, "audio/AMR", data );
response = req.send(data);
} catch (Exception e) {
System.out.println("====Exception: "+e.getMessage());
}
System.out.println("Server Response : "+new String(response));
}
public class PostFile
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;
public PostFile(String url, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
String boundaryMessage = getBoundaryMessage(boundary, fileField, fileName, fileType);
String endBoundary = "\r\n--" + boundary + "--\r\n";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(boundaryMessage.getBytes());
bos.write(fileBytes);
bos.write(endBoundary.getBytes());
this.postBytes = bos.toByteArray();
bos.close();
}
String getBoundaryString()
{
return BOUNDARY;
}
String getBoundaryMessage(String boundary, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
return res.toString();
}
public byte[] send(byte[] fileBytes) throws Exception
{
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH ,Integer.toString(fileBytes.length));
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
dout.close();
int ch;
is = hc.openInputStream(); // <<< EXCEPTION HERE!!!
if(hc.getResponseCode()== HttpConnection.HTTP_OK)
{
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
res = bos.toByteArray();
System.out.println("res loaded..");
}
else {
System.out.println("Unexpected response code: " + hc.getResponseCode());
hc.close();
return null;
}
}
catch(IOException e)
{
System.out.println("====IOException : "+e.getMessage());
}
catch(Exception e1)
{
e1.printStackTrace();
System.out.println("====Exception : "+e1.getMessage());
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
System.out.println("====Exception : "+e2.getMessage());
}
}
return res;
}
}
Highlighted above is the code line which throws the exception: Not Connected.
Can somebody tell me what can be done to correct this? Thanks a lot.
Updated:
public static String getString()
{
String connectionString = null;
String uid = null;
// Wifi
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
else
{
ServiceBook sb = ServiceBook.getSB();
net.rim.device.api.servicebook.ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
if (records[i].isValid() && !records[i].isDisabled()) {
if (records[i].getUid() != null &&
records[i].getUid().length() != 0) {
if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&
(records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
(records[i].getUid().toLowerCase().indexOf("mms") == -1) ) {
uid = records[i].getUid();
break;
}
}
}
}
if (uid != null)
{
connectionString = ";deviceside=true;ConnectionUID="+uid;
}
else
{
// the carrier network
if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the
// carrier's
// TCP network
System.out.println("No Uid");
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier
// BIBS
// request
System.out.println("uid is: " + carrierUid);
connectionString = ";deviceside=false;connectionUID="
+ carrierUid + ";ConnectionType=mds-public";
}
}
//(BlackBerry Enterprise Server)
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging
// the user unnecessarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be
// reachable.
else {
System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
}
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid() {
try {
net.rim.device.api.servicebook.ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals(
"ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
} catch (Exception e) {
System.out.println("====Exception : "+e.toString());
}
return null;
}

Blackberry - How to consume wcf rest services

Recently i have started working on consuming wcf rest webservices in blackberry.
I have used the below two codes:
1.
URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
// passing q’s value and ie’s value
postData.append("UserName", "hsharma#seasiaconsulting.com");
postData.append("Password", "mind#123");
HttpPosst hh=new HttpPosst();
add(new LabelField("1"));
String res=hh.GetResponse("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration",postData);
add(new LabelField("2"));
add(new LabelField(res));
public String GetResponse(String url, URLEncodedPostData data)
{
this._postData = data;
this._url = url;
ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try
{
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// logMessage("Carrier coverage.");
// String carrierUid = getCarrierBIBSUid();
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// logMessage("No Uid");
connectionString = ";deviceside=true";
}
// Check for an MDS connection instead (BlackBerry Enterprise
// Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// logMessage("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the
// user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
// logMessage("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// logMessage("no other options found, assuming device.");
// connectionString = ";deviceside=true";
}
conDesc = conFactory.getConnection(url + connectionString);
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if (null != conDesc)
{
try
{
HttpConnection connection = (HttpConnection) conDesc.getConnection();
// set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length",Integer.toString(data.size()));
// body content of
// post data
connection.setRequestProperty("Connection", "close");
// close
// the
// connection
// after
// success
// sending
// request
// and
// receiving
// response
// from
// the
// server
connection.setRequestProperty("Content-Type","application/json");
// we set the
// content of
// this request
// as
// application/x-www-form-urlencoded,
// because the
// post data is
// encoded as
// form-urlencoded(if
// you print the
// post data
// string, it
// will be like
// this ->
// q=remoQte&ie=UTF-8).
// now it is time to write the post data into OutputStream
OutputStream out = connection.openOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
// when this
// code is
// called,
// the post
// data
// request
// will be
// send to
// server,
// and after
// that we
// can read
// the
// response
// from the
// server if
// the
// response
// code is
// 200 (HTTP
// OK).
if (responseCode == HttpConnection.HTTP_OK)
{
// read the response from the server, if the response is
// ascii character, you can use this following code,
// otherwise, you must use array of byte instead of String
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while ((read = in.read()) != -1)
buf.append((char) read);
response = buf.toString();
}
// don’t forget to close the connection
connection.close();
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
}
return response;
}
public boolean checkResponse(String res)
{
if(!res.equals(""))
{
if(res.charAt(0)=='{')
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
but with this code i am unable to obtain response as what the above wcf web service return
which is({"UserRegistrationResult":[{"OutputCode":"2","OutputDescription":"UserName Already Exists."}]})
Can anybody help me regarding its parsing in blackberry client end.
2.And the another code which i used is:
public class KSoapDemo extends MainScreen
{
private EditField userNametxt;
private PasswordEditField passwordTxt;
private ButtonField loginBtn;
String Username;
String Password;
public KSoapDemo()
{
userNametxt = new EditField("User Name : ", "hsharma#seasiaconsulting.com");
passwordTxt = new PasswordEditField("Password : ", "mind#123");
loginBtn = new ButtonField("Login");
add(userNametxt);
add(passwordTxt);
add(loginBtn);
loginBtn.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert("Hi Satyaseshu..!");
login();
}
});
}
private void login()
{
if (userNametxt.getTextLength() == 0 || passwordTxt.getTextLength() == 0)
{
//Dialog.alert("You must enter a username and password", );
}
else
{
String username = userNametxt.getText();
String password = passwordTxt.getText();
System.out.println("UserName... " + username);
System.out.println("Password... " + password);
boolean value = loginPArse1(username, password);
add(new LabelField("value... " + value));
}
}
public boolean onClose()
{
Dialog.alert("ADIOOO!!");
System.exit(0);
return true;
}
public boolean loginPArse1(String username, String password)
{
username=this.Username;
password=this.Password;
boolean ans = false;
String result = null;
SoapObject request = new SoapObject("http://dotnetstg.seasiaconsulting.com/","UserRegistration");
//request.addProperty("PowerValue","1000");
//request.addProperty("fromPowerUnit","kilowatts");
//request.addProperty("toPowerUnit","megawatts");
request.addProperty("userName",Username);
request.addProperty("Password", Password);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = request;
envelope.dotNet = true;
add(new LabelField("value... " + "1"));
HttpTransport ht = new HttpTransport("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters());
ht.debug = true;
add(new LabelField("value... " + "2"));
//System.out.println("connectionType is: " + connectionType);
try {
ht.call("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration", envelope);
SoapObject body = (SoapObject) envelope.bodyIn;
add(new LabelField("soap....="+body.toString()));
add(new LabelField("property count....="+body.getPropertyCount()));
// add(new LabelField("Result....="+body.getProperty("HelloWorldResult")));
//result = body.getProperty("Params").toString();
// add(new LabelField("value... " + "4"));
ans=true;
}
catch (XmlPullParserException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (IOException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (Exception ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
}
return ans;
}
and in return i am obtain response as net.rim.device.cldc.io.dns.DNS Exception:DNS Error
Please help me in this regard
Thanks And Regards
Pinkesh Gupta
Please have the answer for my own question helps in parsing wcf rest services developed in .net and parsed at blackberry end.
This 2 classess definitely helps in achieving the above code parsing.
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class ConnectionThread extends Thread
{
private boolean start = false;
private boolean stop = false;
private String url;
private String data;
public boolean sendResult = false;
public boolean sending = false;
private String requestMode = HttpConnection.POST;
public String responseContent;
int ch;
public void run()
{
while (true)
{
if (start == false && stop == false)
{
try
{
sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
else if (stop)
{
return;
}
else if (start)
{
http();
}
}
}
private void getResponseContent( HttpConnection conn ) throws IOException
{
InputStream is = null;
is = conn.openInputStream();
// Get the length and process the data
int len = (int) conn.getLength();
if ( len > 0 )
{
int actual = 0;
int bytesread = 0;
byte[] data = new byte[len];
while ( ( bytesread != len ) && ( actual != -1 ) )
{
actual = is.read( data, bytesread, len - bytesread );
bytesread += actual;
}
responseContent = new String (data);
}
else
{
// int ch;
while ( ( ch = is.read() ) != -1 )
{
}
}
}
private void http()
{
System.out.println( url );
HttpConnection conn = null;
OutputStream out = null;
int responseCode;
try
{
conn = (HttpConnection) Connector.open(url);
conn.setRequestMethod(requestMode);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length",Integer.toString(data.length()));
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("SOAPAction","http://dotnetstg.seasiaconsulting.com/");
out = conn.openOutputStream();
out.write(data.getBytes());
out.flush();
responseCode = conn.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
sendResult = false;
responseContent = null;
}
else
{
sendResult = true;
getResponseContent( conn );
}
start = false;
sending = false;
}
catch (IOException e)
{
start = false;
sendResult = false;
sending = false;
}
}
public void get(String url)
{
this.url = url;
this.data = "";
requestMode = HttpConnection.GET;
sendResult = false;
sending = true;
start = true;
}
public void post(String url, String data)
{
this.url = url;
this.data = data;
requestMode = HttpConnection.POST;
sendResult = false;
sending = true;
start = true;
}
public void stop()
{
stop = true;
}
}
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.AutoTextEditField;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.DateField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.MainScreen;
import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.xml.sax.SAXException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.jaxp.SAXParserImpl;
import org.xml.sax.helpers.DefaultHandler;
import java.io.ByteArrayInputStream;
import com.sts.example.ConnectionThread;
import com.sts.example.ResponseHandler;
public class DemoScreen extends MainScreen
{
private ConnectionThread connThread;
private BasicEditField response = new BasicEditField("Response: ", "");
private BasicEditField xmlResponse = new BasicEditField("xml: ", "");
private ButtonField sendButton = new ButtonField("Response");
public DemoScreen(ConnectionThread connThread)
{
this.connThread = connThread;
FieldListener sendListener = new FieldListener();
sendButton.setChangeListener(sendListener);
response.setEditable( false );
xmlResponse.setEditable( false );
add(sendButton);
add(response);
add(new SeparatorField());
add(xmlResponse);
}
public boolean onClose()
{
connThread.stop();
close();
return true;
}
private String getFieldData()
{
//{"UserName":"hsharma#seasiaconsulting.com","Password":"mind#123"}
StringBuffer sb = new StringBuffer();
sb.append("{\"UserNamepinkesh.g#cisinlabs.com\",\"Password\":\"pinkesh1985\"}");
return sb.toString();
}
class FieldListener implements FieldChangeListener
{
public void fieldChanged(Field field, int context)
{
StringBuffer sb = new StringBuffer("Sending...");
connThread.post("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters(), getFieldData());
while (connThread.sending)
{
try
{
Status.show( sb.append(".").toString() );
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (connThread.sendResult)
{
Status.show("Transmission Successfull");
xmlResponse.setText( connThread.responseContent );
try {
JSONObject jsonResponse = new JSONObject(connThread.responseContent);
JSONArray jsonArray = jsonResponse.getJSONArray("UserRegistrationResult");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject result = (JSONObject)jsonArray.get(i);
add(new LabelField("OutputCode"+result.getString("OutputCode")));
add(new LabelField("OutputDescription"+result.getString("OutputDescription")));
}
}
catch (JSONException e)
{
add(new LabelField(e.getMessage().toString()));
e.printStackTrace();
}
}
else
{
Status.show("Transmission Failed");
}
}
}
}

Filter a SharePoint list by audience

I am very new to Sharepoint development. I have the following code that I need to have display the list items by targeted audience. I know I am suppose to add something like this
AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
foreach (SPListItem listItem in list.Items)
{
// get roles the list item is targeted to
string audienceFieldValue = (string)listItem[k_AudienceColumn];
// quickly check if the user belongs to any of those roles
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader,
audienceFieldValue,
false))
But I have no idea where to place it in my code below. Please I would appreciate any of your advise.
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.HtmlControls;
namespace PersonalAnnouncements.PersonalAnnouncements
{
[ToolboxItem(false)]
public class PersonalAnnouncements : Microsoft.SharePoint.WebPartPages.WebPart
{
// Fields
private string _exceptions = "";
private AddInsEnum DE = AddInsEnum.HyperLink;
private const AddInsEnum DefaultAddInsEnum = AddInsEnum.HyperLink;
private const TheDateFormat DefaultDateFormat = TheDateFormat.MonthDayYear;
private const PeriodEnum DefaultPeriod = PeriodEnum.Five;
private const string defaultText = "Your text here";
private const string DefaultURL = "DispForm.aspx";
private TheDateFormat DF = TheDateFormat.MonthDayYear;
private string endField = "Image URL";
private const string imgTURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
private const string imgURL = "/_layouts/NewsViewer/banner1.jpg";
protected Label lblError;
private const string listText = "";
private string listViewFields = "";
private PeriodEnum Period = PeriodEnum.Five;
private string sImageURL = "/_layouts/NewsViewer/banner1.jpg";
private string siteURLtext = "Your Site here";
private string startField = "Body";
private string sTImageURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
private string sTimeField = "/_layouts/NewsViewer/style_smaller.css";
private string sYAxisTitle = "15";
private string text = "Your text here";
private string ThumbImageField = "";
private const string timer = "/_layouts/NewsViewer/style_smaller.css";
private string titleField = "";
private string urltocalendar = "DispForm.aspx";
private const string yaxistit = "15";
// Methods
protected override void CreateChildControls()
{
HtmlTable table;
HtmlTableRow row;
HtmlTableCell cell;
bool controlsAdded = false;
try
{
base.CreateChildControls();
SPWeb theWeb = new SPSite(this.SiteURL).OpenWeb();
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite(theWeb.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[this.Text];
if (list.BaseTemplate == SPListTemplateType.GenericList)
{
this.lblError = new Label();
this.lblError.Text = "Error:";
this.lblError.Visible = true;
HtmlTable child = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
string str = "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + this.CSSField + "\" /><script type=\"text/javascript\" src=\"/_layouts/NewsViewer/jquery-1.3.2.min.js\"></script><script type=\"text/javascript\">var X = jQuery.noConflict();X(document).ready(function() {\t X(\".main_image .desc\").show(); X(\".main_image .block\").animate({ opacity: 0.85 }, 1 ); X(\".image_thumb ul li:first\").addClass('active'); X(\".image_thumb ul li\").click(function(){ var imgAlt = X(this).find('img').attr(\"alt\"); var imgTitle = X(this).find('a').attr(\"href\"); var imgDesc = X(this).find('.block').html(); \t var imgDescHeight = X(\".main_image\").find('.block').height();\t\t if (X(this).is(\".active\")) { return false; } else { X(\".main_image .block\").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() { X(\".main_image .block\").html(imgDesc).animate({ opacity: 0.85,\tmarginBottom: \"0\" }, 250 ); X(\".main_image img\").attr({ src: imgTitle , alt: imgAlt}); }); } X(\".image_thumb ul li\").removeClass('active'); X(this).addClass('active'); return false;}) .hover(function(){ X(this).addClass('hover'); }, function() { X(this).removeClass('hover');}); X(\"a.collapse\").click(function(){ X(\".main_image .block\").slideToggle(); X(\"a.collapse\").toggleClass(\"show\"); });}); </script><div id=\"main\" class=\"container\">";
string sideNav = this.GetSideNav();
string mainContent = this.GetMainContent();
cell.InnerHtml = str + mainContent + sideNav + "</div></div>";
row.Cells.Add(cell);
child.Rows.Add(row);
this.Controls.Add(child);
controlsAdded = true;
}
}
}
});
}
catch (Exception exception)
{
if (controlsAdded)
{
this._exceptions = this._exceptions + "CreateChildControls_Exception: " + exception.Message;
}
table = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
if (!this.Text.Contains("Your text here"))
{
cell.InnerHtml = "Error: " + exception.Message;
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
this.Controls.Add(this.lblError);
}
}
if (!controlsAdded)
{
table = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
if (!this.Text.Contains("Your text here"))
{
cell.InnerHtml = "Please choose the Personal Announcement list: " + this.Text + " - Site:" + this.SiteURL;
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
this.Controls.Add(this.lblError);
}
else
{
cell.InnerHtml = "Please setup Personal Announcement by clicking Modify Shared WebPart";
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
}
}
}
private string FirstWords(string input, int numberWords)
{
try
{
int num = numberWords;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ' ')
{
num--;
}
if (num == 0)
{
return input.Substring(0, i);
}
}
}
catch (Exception)
{
}
return string.Empty;
}
private string GetMainContent()
{
string str = "";
this.lblError.Text = this.lblError.Text + " -> GetMainContent()";
SPSite site = new SPSite(this.SiteURL);
SPWeb web = site.OpenWeb();
SPUserToken userToken = site.SystemAccount.UserToken;
using (SPSite site2 = new SPSite(web.Url, userToken))
{
using (SPWeb web2 = site2.OpenWeb())
{
SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
view.RowLimit = 1;
SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
int num = 0;
int num2 = this.getNumber(this.NumEvents.ToString());
string str2 = "";
if (items.Count > 0)
{
foreach (SPListItem item in items)
{
if (num == 0)
{
object obj2;
string imageURL = "";
string format = "";
if (this.DateFormat.ToString() == "DayMonthYear")
{
format = "d/M/yyyy HH:mm tt";
}
else
{
format = "M/d/yyyy HH:mm tt";
}
if (item[this.ImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString();
}
else
{
imageURL = this.ImageURL;
}
}
else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageURL = this.ImageURL;
}
}
else
{
imageURL = this.ImageURL;
}
str2 = str2 + "<div class=\"main_image\">";
str2 = str2 + "<img src=\"" + imageURL + "\" alt=\"BNNewsbanner\" />";
str2 = str2 + "<div class=\"desc\" >Close Me!";
if (item[this.TitleField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No Title Text Found</a></h2>" });
}
str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
if (item[this.BodyField] != null)
{
obj2 = str2;
// str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
}
}
num++;
}
}
str = str + str2;
}
}
return str;
}
public int getNumber(string number)
{
switch (number)
{
case "One":
return 1;
case "Two":
return 2;
case "Three":
return 3;
case "Four":
return 4;
case "Five":
return 5;
case "Six":
return 6;
case "Seven":
return 7;
case "Eight":
return 8;
case "Nine":
return 9;
case "Ten":
return 10;
}
return 0;
}
private string GetSideNav()
{
this.lblError.Text = this.lblError.Text + " -> GetSideNav()";
string str = "<div class=\"image_thumb\"><ul>";
SPSite site = new SPSite(this.SiteURL);
SPWeb web = site.OpenWeb();
SPUserToken userToken = site.SystemAccount.UserToken;
using (SPSite site2 = new SPSite(web.Url, userToken))
{
using (SPWeb web2 = site2.OpenWeb())
{
SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
int num = 0;
int num2 = this.getNumber(this.NumEvents.ToString());
string str2 = "";
if (items.Count > 0)
{
foreach (SPListItem item in items)
{
if (num < num2)
{
object obj2;
string imageThumbURL = "";
string imageURL = "";
string format = "";
if (this.DateFormat.ToString() == "DayMonthYear")
{
format = "d/M/yyyy HH:mm tt";
}
else
{
format = "M/d/yyyy HH:mm tt";
}
if (item[this.ImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString();
}
else
{
imageURL = this.ImageURL;
}
}
else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageURL = this.ImageURL;
}
}
else
{
imageURL = this.ImageURL;
}
if (item[this.ThumbImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
{
imageThumbURL = item[this.ThumbImageURLField].ToString();
}
else
{
imageThumbURL = this.ImageThumbURL;
}
}
else if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
{
imageThumbURL = item[this.ThumbImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageThumbURL = this.ImageThumbURL;
}
}
else
{
imageThumbURL = this.ImageThumbURL;
}
str2 = str2 + "<li><a href=\"" + imageURL + "\">";
str2 = str2 + "<img src=\"" + imageThumbURL + "\" alt=\"\" /></a>";
if (item[this.TitleField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No List Title Found</a></h2>" });
}
str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
if (item[this.BodyField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" });
}
}
num++;
}
}
str = str + str2;
}
}
return (str + "</ul>");
}
public override ToolPart[] GetToolParts()
{
ToolPart[] partArray = new ToolPart[3];
WebPartToolPart part = new WebPartToolPart();
CustomPropertyToolPart part2 = new CustomPropertyToolPart();
partArray[0] = part2;
partArray[1] = part;
partArray[2] = new CustomToolPart();
return partArray;
}
protected override void RenderContents(HtmlTextWriter writer)
{
try
{
base.RenderContents(writer);
}
catch (Exception exception)
{
this._exceptions = this._exceptions + "RenderContents_Exception: " + exception.Message;
}
finally
{
if (this._exceptions.Length > 0)
{
writer.WriteLine(this._exceptions);
}
}
}
private string StripTagsCharArray(string source)
{
char[] chArray = new char[source.Length];
int index = 0;
bool flag = false;
for (int i = 0; i < source.Length; i++)
{
char ch = source[i];
if (ch == '<')
{
flag = true;
}
else if (ch == '>')
{
flag = false;
}
else if (!flag)
{
chArray[index] = ch;
index++;
}
}
return new string(chArray, 0, index);
}
// Properties
public string BodyField
{
get
{
return this.startField;
}
set
{
this.startField = value;
}
}
[WebDisplayName("Style Sheet URL"), WebDescription("Specifies the path to the css file"), SPWebCategoryName("General Settings"), Personalizable(true), WebBrowsable(true)]
public string CSSField
{
get
{
return this.sTimeField;
}
set
{
this.sTimeField = value;
}
}
[WebBrowsable(true), Personalizable(true), WebDisplayName("Date Format"), WebDescription("Date Format of your News Items"), SPWebCategoryName("General Settings")]
public TheDateFormat DateFormat
{
get
{
return this.DF;
}
set
{
this.DF = value;
}
}
[WebBrowsable(true), WebDescription("Thumb Image URL to use when no image is found"), SPWebCategoryName("General Settings"), Personalizable(true), WebDisplayName("No Thumb Image URL")]
public string ImageThumbURL
{
get
{
return this.sTImageURL;
}
set
{
this.sTImageURL = value;
}
}
[Personalizable(true), SPWebCategoryName("General Settings"), WebBrowsable(true), WebDisplayName("No Image URL"), WebDescription("Image URL to use when no image is found")]
public string ImageURL
{
get
{
return this.sImageURL;
}
set
{
this.sImageURL = value;
}
}
public string ImageURLField
{
get
{
return this.endField;
}
set
{
this.endField = value;
}
}
public string ListViewFields
{
get
{
return this.listViewFields;
}
set
{
this.listViewFields = value;
}
}
[WebDescription("Number of news items to show"), WebDisplayName("Number of news items to show"), WebBrowsable(true), SPWebCategoryName("General Settings"), Personalizable(true)]
public PeriodEnum NumEvents
{
get
{
return this.Period;
}
set
{
this.Period = value;
}
}
[WebDisplayName("Number of words to show from the Body"), Personalizable(true), SPWebCategoryName("General Settings"), WebDescription("Specifies the number of words to show from the body in the main webpart, under the Title"), WebBrowsable(true)]
public string NumWords
{
get
{
return this.sYAxisTitle;
}
set
{
this.sYAxisTitle = value;
}
}
public string SiteURL
{
get
{
return this.siteURLtext;
}
set
{
this.siteURLtext = value;
}
}
public string Text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
[Personalizable(true), SPWebCategoryName("General Settings"), WebDisplayName("Image Column Type")
You can put the code in CreateChildControls() method.

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