I'm trying to use a third party dll called ASPTokenInputLib in my sharepoint2013 webpart .
It was working for a while when I loaded it in the bin directory but when I tried to move it to the GAC it won't work and it's stopped working if I load it in the bin now as well.
The error I get is object reference not set to an instance of an object. The sharepoint logs shows
System.NullReferenceException: Object reference not set to an instance of an object. at ASPTokenInputLib.ASPTokenInput.OnLoad(EventArgs e)
My package manifest file includes
<Assemblies>
<Assembly Location="ASPTokenInputLib.dll" DeploymentTarget="GlobalAssemblyCache" />
<Assembly Location="BidSearchWebPart.dll" DeploymentTarget="GlobalAssemblyCache">
<SafeControls>
<SafeControl Assembly="BidSearchWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=59049686a9425568" Namespace="BidSearchWebPart.VisualWebPart1" TypeName="*" />
</SafeControls>
</Assembly>
If I remove any ASPTokenInput controls in the webpart the webpart loads correctly so I don't think there's a problem finding the control in the gac (I've used process monitor and it is looking in the correct place in the GAC to find the control). For some reason though it can't load the dll.
Any help would be much appreciated. Thanks!
My ascx.cs files is
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Web.Script.Serialization;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using ASPTokenInputLib;
namespace BidSearchWebPart.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public partial class BidSearchWebPart : WebPart
{
private enum Columns
{
BidRef, BidName, Client, Area, TeamLead
}
private string TeamLeadsData, ExecLeadsData, StagesData, SectorsData, ServicesData, GradesData, CostCentresData, ClientsData, AreasData;
public BidSearchWebPart()
{
TeamLeadsData = RunSP("uspSelectTeamLeads", "TeamLead", "Name", ConnectionString());
ExecLeadsData = RunSP("uspSelectExecTechLeads", "ExecutiveTechnicalLead", "Name", ConnectionString());
StagesData = RunSP("uspSelectStages", "StageID", "StageDescSearch", ConnectionString());
SectorsData = RunSP("spSelectMarketSectors", "SectorID", "MktSector", CCDConnectionString());
ServicesData = RunSP("spSelectAllServices", "ServiceID", "Service", CCDConnectionString());
GradesData = RunSP("uspSelectGrades", "GradeID", "GradeDesc", ConnectionString());
CostCentresData = RunSP("uspSelectCostCentres", "CostCentre", "Name", ConnectionString());
ClientsData = RunSP("spSelectAllClients", "CompanyRef", "CoName", CCDConnectionString());
AreasData = RunSP("uspSelectAreas", "AreaID", "AreaName", ConnectionString());
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
List<string> ddValues = new List<string>();
if (!Page.IsPostBack)
{
ddValues.Add("Greater than");
ddValues.Add("Less than");
ddCC.DataSource = ddValues;
ddFV.DataSource = ddValues;
ddCC.DataBind();
ddFV.DataBind();
}
btnSearch.Click += btnSearch_Click;
gvSearchResults.RowDataBound += gvSearchResults_RowDataBound;
tiTeamLead.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiTeamLead.DataSet = TeamLeadsData;
tiExecTechLead.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiExecTechLead.DataSet = ExecLeadsData;
tiStage.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiStage.DataSet = StagesData;
tiSector.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiSector.DataSet = SectorsData;
tiService.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiService.DataSet = ServicesData;
tiGrade.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiGrade.DataSet = GradesData;
tiCostCentre.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiCostCentre.DataSet = CostCentresData;
tiClient.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiClient.DataSet = ClientsData;
tiArea.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiArea.DataSet = AreasData;
}
void btnSearch_Click(object sender, EventArgs e)
{
//if (string.IsNullOrEmpty(txtProjectNo.Text) && string.IsNullOrEmpty(txtProjectName.Text) && string.IsNullOrEmpty(txtClient.Text) && string.IsNullOrEmpty(txtKeyword.Text)) // Do nothing if search text boxes are blank
//{
// return;
//} else {
gvSearchResults.PageIndex = 0;
DoSearch();
//}
}
protected void gvSearchResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvSearchResults.PagerTemplate = null;
gvSearchResults.PageIndex = e.NewPageIndex;
DoSearch();
}
public void DoSearch()
{
DataTable dt = new DataTable();
string where = GetWhereClause();
if (!string.IsNullOrEmpty(where))
{
dt = FillTable("spSelectBidSearchResults", where);
}
gvSearchResults.DataSource = dt;
gvSearchResults.PageSize = 10;
gvSearchResults.PagerTemplate = null;
gvSearchResults.DataBind();
}
private DataTable FillTable(string storedProc, string where)
{
SqlConnection conn = new SqlConnection(ConnectionString());
conn.Open();
SqlCommand cmdProject = new SqlCommand(storedProc, conn);
cmdProject.CommandType = CommandType.StoredProcedure;
cmdProject.Parameters.AddWithValue("#whereclause", where);
SqlDataAdapter da = new SqlDataAdapter(cmdProject);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
conn.Close();
return dt;
}
private string Symbol(string ddText)
{
if (ddText.Equals("Greater than"))
{
return ">";
}
else
{
return "<";
}
}
private string GetWhereClause()
{
string where = "";
where = GetWhereForCol(txtBidName.Text, "", "BidName", "like", where);
where = GetWhereForCol(txtDescription.Text, "", "Description", "like", where);
where = GetWhereForCol(GetTokens(tiTeamLead), "", "TeamLead", "token", where);
where = GetWhereForCol(GetTokens(tiExecTechLead), "", "ExecutiveTechnicalLead", "token", where);
where = GetWhereForCol(txtConstructionCost.Text, ddCC.Text, "ConstructionCost", "numeric", where);
where = GetWhereForCol(txtFeeValue.Text, ddFV.Text, "FeeValue", "numeric", where);
where = GetWhereForCol(GetTokens(tiStage), "", "Stage", "token", where);
where = GetWhereForCol(GetTokens(tiSector), "", "PrimarySector", "token", where, "SecondarySector");
where = GetWhereForCol(GetTokens(tiService), "", "PrimaryService", "token", where);
where = GetWhereForCol(GetTokens(tiGrade), "", "Grade", "token", where);
where = GetWhereForCol(GetTokens(tiCostCentre), "", "PrimaryCostCentre", "token", where);
where = GetWhereForCol(GetTokens(tiClient), "", "ClientRef", "token", where);
where = GetWhereForCol(GetTokens(tiArea), "", "Area", "token", where);
return where;
}
private string GetWhereForCol(string text, string ddText, string colName, string colType, string where, string otherCol = "")
{
if (!string.IsNullOrEmpty(text))
{
if (colType.Equals("like"))
{
where = AddToWhere(where, colName + " LIKE '%" + text + "%'");
}
else if (colType.Equals("numeric"))
{
string symbl = Symbol(ddText);
where = AddToWhere(where, colName + " " + symbl + " " + text);
}
else if (colType.Equals("token"))
{
if (!string.IsNullOrEmpty(otherCol))
{
where = AddToWhere(where, "(" + colName + " in (" + text + ")");
where += " OR " + otherCol + " in (" + text + "))";
}
else
{
where = AddToWhere(where, colName + " in (" + text + ")");
}
}
}
return where;
}
private string AddToWhere(string where, string clause)
{
if (!string.IsNullOrEmpty(clause))
{
if (string.IsNullOrEmpty(where))
{
where = clause;
}
else
{
where += " AND " + clause;
}
}
return where;
}
private string GetTokens(ASPTokenInput ti)
{
StringBuilder strTokens = new StringBuilder();
List<ASPTokenInput.Item> items = ti.SelectedItems;
foreach (ASPTokenInput.Item item in items)
{
if (strTokens.Length > 0)
{
strTokens.Append(", ");
}
strTokens.AppendFormat("'{0}'", item.id);
}
return strTokens.ToString();
}
public string GetSPSingleValue(string spName, string spParamName, string spParamVal, string connectionStr)
{
try
{
SqlConnection conn = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(spName, conn);
cmd.Parameters.AddWithValue(spParamName, spParamVal);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
string result = cmd.ExecuteScalar().ToString();
conn.Close();
return result;
}
catch
{
return "";
}
}
void gvSearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l;
DataRowView rowView = (DataRowView)e.Row.DataItem;
string bidRef = rowView["BidRef"].ToString();
string teamLeadID = rowView["TeamLead"].ToString();
string teamLeadName = GetSingleRecord("uspSelectTeamLeadByID", ConnectionString(), "#TeamLead", teamLeadID);
l = (Label)e.Row.Cells[(int)Columns.TeamLead].FindControl("lblTeamLead");
l.Text = teamLeadName;
if (siteCollectionExists(bidRef))
{
l = (Label)e.Row.Cells[(int)Columns.BidRef].FindControl("lblBidRef");
HyperLink hl = new HyperLink();
hl.NavigateUrl = "http://bidstore.gleeds.net/bids/" + bidRef;
hl.Text = bidRef;
e.Row.Cells[(int)Columns.BidRef].Controls.Add(hl);
l.Text = "";
}
}
}
//Check if site collection exists at given web application
private static bool siteCollectionExists(string bidNr)
{
bool returnVal = false;
var r = SPContext.Current.Site.WebApplication.Sites.Where(site => site.Url.Contains(bidNr));
foreach (SPSite s in r)
{
returnVal = true;
}
return returnVal;
}
public string TeamLeads()
{
return TeamLeadsData;
}
public string ExecutiveTechnicalLeads()
{
return ExecLeadsData;
}
public string Stages()
{
return StagesData;
}
public string Sectors()
{
return SectorsData;
}
public string Services()
{
return ServicesData;
}
public string Grades()
{
return GradesData;
}
public string CostCentres()
{
return CostCentresData;
}
public string Clients()
{
return ClientsData;
}
public string Areas()
{
return AreasData;
}
public string GetSingleRecord(string spName, string connectionStr, string param, string value)
{
SqlConnection conn = new SqlConnection();
SqlCommand command = new SqlCommand(spName, conn);
conn = new SqlConnection(connectionStr);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue(param, value);
command.Connection = conn;
conn.Open();
string result = command.ExecuteScalar().ToString();
conn.Close();
return result;
}
public string RunSP(string spName, string idCol, string nameCol, string connectionStr)
{
ArrayList data = new ArrayList();
SqlConnection conn = new SqlConnection();
SqlCommand command = new SqlCommand(spName, conn);
conn = new SqlConnection(connectionStr);
command.CommandType = CommandType.StoredProcedure;
command.Connection = conn;
conn.Open();
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
data.Add(new TokenInputRow(dr[idCol].ToString(), dr[nameCol].ToString()));
}
conn.Close();
return Serialize(data);
}
private static string Serialize(object obj)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(obj);
}
private string ConnectionString()
{
return "Data Source=10.2.40.17;Initial Catalog=BidOpening;Persist Security Info=True;User ID=GTL_BidOpening_User;Password=G#rd3n12";
}
private string CCDConnectionString()
{
return "Data Source=10.2.40.17;Initial Catalog=CCDLive;Persist Security Info=True;User ID=GTL_CCDLive_User;Password=G#rd3n";
}
}
public class TokenInputRow
{
public string id;
public string name;
public TokenInputRow(string _id, string _name)
{
id = _id;
name = _name;
}
}
}
I am able to step through the page load, but I can't step into the ASPTokenInput dll. The code fails after the page load has finished.
The ti controls are included in my .ascx file as so %# Register TagPrefix="ati" Assembly="ASPTokenInputLib" Namespace="ASPTokenInputLib" %> ati:ASPTokenInput ID="tiTeamLead" runat="server" HintText="Start typing TeamLead..." />
Related
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();
}
}
I am trying to set or write the result of execute test cases using JXL in key driven framework. Also, I am able to write or set the result but only in first iteration. At the time of second iteration it shows null pointer exception. I tried but don't understand what the exact problem is?
Main Method:
public class MainClass {
private static final String BROWSER_PATH = "D:\\FF18\\firefox.exe";
private static final String TEST_SUITE_PATH = "D:\\configuration\\GmailTestSuite.xls";
private static final String OBJECT_REPOSITORY_PATH = "D:\\configuration\\objectrepository.xls";
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
// other constants
private WebDriver driver;
private Properties properties;
/* private WebElement we; */
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws Exception {
MainClass main = new MainClass();
main.handleTestSuite();
}
private void handleTestSuite() throws Exception {
ReadPropertyFile readConfigFile = new ReadPropertyFile();
properties = readConfigFile.loadPropertiess();
ExcelHandler testSuite = new ExcelHandler(TEST_SUITE_PATH, "Suite");
testSuite.columnData();
int rowCount = testSuite.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int i = 1; i < rowCount; i++) {
String executable = testSuite.readCell(
testSuite.getCell("Executable"), i);
System.out.println("Executable=" + executable);
if (executable.equalsIgnoreCase("y")) {
// exe. the process
String scenarioName = testSuite.readCell(
testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name=" + scenarioName);
handleScenario(scenarioName);
}
}
WritableData writableData= new WritableData(TEST_SUITE_PATH,"Login");
writableData.shSheet("Login", 5, 1, "Pass");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
writableData.shSheet("Login", 5, 2, "Fail");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
writableData.shSheet("Login", 5, 3, "N/A");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
private void handleScenario(String scenarioName) throws Exception {
ExcelHandler testScenarios = new ExcelHandler(TEST_SUITE_PATH);
testScenarios.setSheetName("Login");
testScenarios.columnData();
int rowWorkBook1 = testScenarios.rowCount();
for (int j = 1; j < rowWorkBook1; j++) {
String framWork = testScenarios.readCell(
testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(
testScenarios.getCell("Operation"), j); // SendKey
String value = testScenarios.readCell(
testScenarios.getCell("Value"), j);
System.out.println("FRMNameKK=" + framWork + ",Operation="
+ operation + ",Value=" + value);
handleObjects(operation, value, framWork);
}
}
private void handleObjects(String operation, String value, String framWork)
throws Exception {
System.out.println("HandleObject--> " + framWork);
ExcelHandler objectRepository = new ExcelHandler(
OBJECT_REPOSITORY_PATH, "OR");
objectRepository.columnData();
int rowCount = objectRepository.rowCount();
System.out.println("Total Rows in hadleObject=" + rowCount);
for (int k = 1; k < rowCount; k++) {
String frameWorkName = objectRepository.readCell(
objectRepository.getCell("FrameworkName"), k);
String ObjectName = objectRepository.readCell(
objectRepository.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(
objectRepository.getCell("Locator"), k); // SendKey
System.out.println("FrameWorkNameV=" + frameWorkName
+ ",ObjectName=" + ObjectName + ",Locator=" + Locator);
if (framWork.equalsIgnoreCase(frameWorkName)) {
operateWebDriver(operation, Locator, value, ObjectName);
}
}
}
private void operateWebDriver(String operation, String Locator,
String value, String objectName) throws Exception {
System.out.println("Operation execution in progress");
WebElement temp = getElement(Locator, objectName);
if (operation.equalsIgnoreCase("SendKey")) {
temp.sendKeys(value);
}
Thread.sleep(1000);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
if (operation.equalsIgnoreCase("Click")) {
temp.click();
}
if (operation.equalsIgnoreCase("Verify")) {
System.out.println("Verify--->" +temp);
temp.isDisplayed();
}
}
public WebElement getElement(String locator, String objectName)
throws Exception {
WebElement temp = null;
System.out.println("Locator-->" + locator);
if (locator.equalsIgnoreCase("id")) {
temp = driver.findElement(By.id(objectName));
} else if (locator.equalsIgnoreCase("xpath")) {
temp = driver.findElement(By.xpath(objectName));
System.out.println("xpath temp ----->" + temp);
} else if (locator.equalsIgnoreCase("name")) {
temp = driver.findElement(By.name(objectName));
}
return temp;
}
}
WritableData
public class WritableData {
Workbook wbook;
WritableWorkbook wwbCopy;
String ExecutedTestCasesSheet;
WritableSheet shSheet;
public WritableData(String testSuitePath, String OBJECT_REPOSITORY_PATH) throws RowsExceededException, WriteException {
// TODO Auto-generated constructor stub
try { wbook = Workbook.getWorkbook(new File(testSuitePath));
wwbCopy= Workbook.createWorkbook(new File(testSuitePath),wbook);
System.out.println("writable workbookC-->" +wwbCopy);
shSheet=wwbCopy.getSheet("Login");
System.out.println("writable sheetC-->" +shSheet);
//shSheet = wwbCopy.createSheet("Login", 1);
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception message" + e.getMessage()); e.printStackTrace(); } }
public void shSheet(String strSheetName, int iColumnNumber, int
iRowNumber, String strData) throws WriteException, IOException {
// TODO Auto-generated method stub
System.out.println("strDataCC---->>" +strData);
System.out.println("strSheetName<<>><<>><<>>" +strSheetName);
WritableSheet wshTemp = wwbCopy.getSheet(strSheetName);
shSheet=wwbCopy.getSheet("Login");
WritableFont cellFont = null;
WritableCellFormat cellFormat = null;
if (strData.equalsIgnoreCase("PASS")) {
cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.GREEN);
cellFont.setBoldStyle(WritableFont.BOLD);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN); }
else if (strData.equalsIgnoreCase("FAIL")) {
cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.RED);
cellFont.setBoldStyle(WritableFont.BOLD);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN); }
else { cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.BLACK);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
cellFormat.setWrap(true); }
Label labTemp = new Label(iColumnNumber, iRowNumber, strData,
cellFormat);
shSheet.addCell(labTemp);
System.out.println("writableSheet---->"+shSheet);
wwbCopy.write();
wwbCopy.close();
wbook.close();
}
}
Console:
writable sheetC-->jxl.write.biff.WritableSheetImpl#ee1ede
strDataCC---->>Pass
strSheetName<<>><<>><<>>Login
writableSheet---->jxl.write.biff.WritableSheetImpl#ee1ede
strDataCC---->>Fail
strSheetName<<>><<>><<>>Login
writableSheet---->jxl.write.biff.WritableSheetImpl#ee1ede
Exception in thread "main" java.lang.NullPointerException
at jxl.write.biff.File.write(File.java:149)
at jxl.write.biff.WritableWorkbookImpl.write(WritableWorkbookImpl.java:706)
at com.chayan.af.WritableData.shSheet(WritableData.java:86)
at com.chayan.af.MainClass.handleTestSuite(MainClass.java:77)
at com.chayan.af.MainClass.main(MainClass.java:48)
This is my code i have done it for my project to genrate a pdf report
public partial class Report : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
getreport();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
// base.VerifyRenderingInServerForm(control);
}
public void getreport()
{
string province = Request.QueryString["Province"].ToString();
string district = Request.QueryString["District"].ToString();
string village = Request.QueryString["Village"].ToString();
ReportViewer1.ProcessingMode = ProcessingMode.Local;
LocalReport rep = ReportViewer1.LocalReport;
rep.ReportPath = #"Report.rdlc";
ReportDataSource dsRep = new ReportDataSource();
dsRep.Name = "DataSet1";
dsRep.Value = GetDataTable(province, district, village);
rep.DataSources.Clear();
rep.DataSources.Add(dsRep);
//ReportViewer1.DocumentMapCollapsed = true;
//ReportViewer1.ShowPrintButton = true;
//rep.Render("PDF");
byte[] result = null;
result = rep.Render("PDF");
Response.ClearContent();
Response.AppendHeader("content-length", result.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(result);
Response.Flush();
Response.Close();
rep.Refresh();
}
protected DataTable GetDataTable(string p,string d,string v)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
DataTable dt;
SqlDataAdapter da;
SqlCommand cmd;
string filter = "";
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
cmd = new SqlCommand("select '" +p + "' as UserName, '"+d+"'Password,'"+ v+"' as category", con);
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
cmd.Dispose();
con.Close();
return dt;
}
catch (Exception ex)
{
return null;
}
}
The Render method does have an overload that takes one parameter in .NET 4.0, but not in previous versions.
You'll have to call the (String, String, out String, out String, out String, out String[], out Warning[]) overload as below.
string extension;
string encoding;
string mimeType;
string extension;
string[] streams;
Warning[] warnings;
result = rsExec.Render("PDF", null,
out extension, out encoding,
out mimeType, out streams, out warnings);
i want to know the method used to update record in recordstore in j2me. thanks....
Simply use RecordStore.setRecord()
try this
Preferences preferences = new Preferences("ChatAppPref");
preferences.put("login", "y");
preferences.save();
String pIsLogin = preferences.get("login");
Preferences class here
package com.util;
import java.util.*;
import javax.microedition.rms.*;
public class Preferences {
private String mRecordStoreName;
private Hashtable mHashtable;
public Preferences(String recordStoreName)
throws RecordStoreException {
mRecordStoreName = recordStoreName;
mHashtable = new Hashtable();
load();
}
public String get(String key) {
return (String)mHashtable.get(key);
}
public void put(String key, String value) {
if (value == null) value = "";
mHashtable.put(key, value);
}
private void load() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
byte[] raw = re.nextRecord();
String pref = new String(raw);
// Parse out the name.
int index = pref.indexOf('|');
String name = pref.substring(0, index);
String value = pref.substring(index + 1);
put(name, value);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
public void save() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
// First remove all records, a little clumsy.
while (re.hasNextElement()) {
int id = re.nextRecordId();
rs.deleteRecord(id);
}
// Now save the preferences records.
Enumeration keys = mHashtable.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = get(key);
String pref = key + "|" + value;
byte[] raw = pref.getBytes();
rs.addRecord(raw, 0, raw.length);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
}
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.