ArgumentNull exception in asp.net web application - asp.net

I have developed an asp.net application in which input will be given through an excel sheet.
This application is working fine in a system with WINDOWS XP and MS office 2008.
If i try to run the same application in a system with WINDOWS 7 and MS office 2010 i am getting a Argument Null Exception.
Code:
foreach (var dr in data)
{
LHSupdate = new LHSUpdate();
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Id"])))
{
AssociateID = Convert.ToString(dr["Associate Id"]);
}
LHSupdate.AssciateID = AssociateID;
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Name"])))
{
AssociateName = Convert.ToString(dr["Associate Name"]);
}
LHSupdate.Name = AssociateName;
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
if (designation != null)
{
foreach (var de in designation)
{
LHSupdate.Designation = Convert.ToString(de["Level"]);
}
}
else
{
LHSupdate.Designation = "";
}
LHSupdate.CourseName = Convert.ToString(dr["Trainings "]);
LHSupdate.CourseStatus = Convert.ToString(dr["Training Status"]);
LHSupdate.Score = Convert.ToString(dr["Credits"]);
LHSupdate.LearningMode = Convert.ToString(dr["Venue"]);
LHSupdate.StartDate = Convert.ToString(dr["Start Date"]);
LHSupdate.EndDate = Convert.ToString(dr["End Date"]);
lstLHS.Add(LHSupdate);
}
I am getting error in the line:
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
Code:
private DataSet Getdata()
{
string connectionString = "";
string getExcelSheetName = string.Empty;
if (fuLHSEntry.HasFile)
{
string fileName = Path.GetFileName(fuLHSEntry.PostedFile.FileName);
string fileExtension = Path.GetExtension(fuLHSEntry.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
fuLHSEntry.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 8.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();
}
else if (fileExtension == ".xlsx" || fileExtension == ".xlsm")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 12.0;IMEX=2;HDR=Yes;" + Convert.ToChar(34).ToString();
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
int count = 0;
foreach (DataRow dr in dtExcelSheetName.Rows)
{
getExcelSheetName = GetSheetName(dr);
if (!string.IsNullOrEmpty(getExcelSheetName))
{
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
if (getExcelSheetName.ToUpper().Contains("LEARNING"))
{
getExcelSheetName = "LEARNING";
}
else
{
getExcelSheetName = "LHS";
}
dAdapter.Fill(dsData, getExcelSheetName);
count++;
if (count == 2)
{
break;
}
}
}
con.Close();
}
return dsData;
}
Please help me in resolving this issue.
Thanks,
Raji

From your code it appears that the table can have two possible names.
Either give it always the same name that you're using later when reading:
dAdapter.Fill(dsData, "LHS");
Or you can take the table by index ignoring its name altogether:
var designation = dsData.Tables[0].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());

Related

What is ZRangeValid means

This code is to read an excel file, what is ZRangeValid means and what is rs.fields(0).value referring to? Please explain my two questions
var strConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strXLPath + ";Extended Properties=\"Excel 12.0;HDR=YES;\";";
var conn = new ActiveXObject("ADODB.Connection");
conn.open(strConnString, "", "");
var rs = new ActiveXObject("ADODB.Recordset");
var rsrowCount = new ActiveXObject("ADODB.Recordset");
rs = conn.execute("select * from ZRangeValid");
if (rs.fields(0).value != 'YES') {
alert(strXLPath + " requested numbers spreadsheet is not valid.\nPlease validate the spreadsheet data and retry.")
rs = null;
rsSheet = null;
conn.close();
conn = null;
return false
}

Jquery Ajax JSON data read is not working

I'm trying to retrieve data from SQL server DB and convert it to JSON and try to show the json data using JQuery Ajax function, here is the C# code,
C#
public String GetData()
{
try
{
String strjson;
string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionstring);
DataSet DS = new DataSet();
String CmdText = "Select Compname,compadd1,compadd2,compemail from company where compid=#cmpid";
SqlCommand cmd = new SqlCommand(CmdText, Con);
cmd.Parameters.Add("#cmpid", SqlDbType.Int).Value = 22;
Con.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
DataTable dTable = DS.Tables[0];
strjson = GetJSONString(dTable);
Con.Close();
return strjson;
}
catch (Exception ex)
{
throw new System.Exception("Error In Get Data" + ex.Message);
}
}
the GetJSONString(dTable) function working fine, here is the JQuery code,
jQuery & HTML
<form id="form1" runat="server">
<div>
<h1>JSON Sample</h1>
<button id="getdata">Get Data</button>
<div id="company"></div>
<%-- <asp:Button ID="aspbutton" runat="server" Text=".Net Call" OnClick="btnOn_Click" />
<asp:GridView runat="server" ID="grdview"></asp:GridView>--%>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#getdata").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "",
url: "Default.aspx/GetData",
dataType: "json",
success: function (data) {
alert(data.d);
$("#company").html(data.d);
}
});
});
});
</script>
</form>
I have included the jQuery file, please let me know if I have made any mistake,
EDITED :GetJSONString added
public static string GetJSONString(DataTable Dt)
{
string[] StrDc = new string[Dt.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < Dt.Columns.Count; i++)
{
StrDc[i] = Dt.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + Dt.TableName + "\" : [");
for (int i = 0; i < Dt.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < Dt.Columns.Count; j++)
{
switch (Dt.Columns[j].DataType.ToString())
{
case "System.DateTime":
DateTime cv = (DateTime)Dt.Rows[i][j];
TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", cv.Year + "," + (cv.Month - 1) + "," + cv.Day + "," + cv.Hour + "," + cv.Minute + "," + cv.Second + "," + cv.Millisecond);
break;
case "System.Boolean":
TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString().ToLower());
break;
default:
string str = Dt.Rows[i][j].ToString();
str = str.Replace("\n", "\\\\n");
str = str.Replace("\\", "\\\\\\\\");
str = str.Replace("\"", "ppp");
str = str.Replace("'", "\\\'");
str = str.Replace("\r", "\\\\r");
TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", str);
break;
}
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
I added error: section in Ajax call, now getting the error "error; [object Object]"
Finally, I found what was the issue, I have to add "[WebMethod()]" declaration just before the asp.net function. For example,
[WebMethod()]
public static string GetData()
{
try
{
string strjson;
string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionstring);
DataSet DS = new DataSet();
String CmdText = "Select Compname,compadd1,compadd2,compemail from aas_company where compid=#cmpid";
SqlCommand cmd = new SqlCommand(CmdText, Con);
cmd.Parameters.Add("#cmpid", SqlDbType.Int).Value = 22;
Con.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
DataTable dTable = DS.Tables[0];
strjson = GetJSONString(dTable);
Con.Close();
return strjson;
}
catch (Exception ex)
{
throw new System.Exception("Error In Get Data" + ex.Message);
}
}

Label does not show up in asp.net

I have a label in asp.net page and change its text in certain situations. Here is the code:
<asp:Label ID="errorMessage" runat="server" Text="Label" Visible="False"></asp:Label>
errorMessage.Text = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
When i debugged, i saw that MyGlobals.student.registerCourse(c, ref addList, course).ToString() method returns my error message well. Then i set the label visible, but when page loads i cannot see the label. Also, while debugging i saw that "textsetbyaddparsedsubobject" property of the label is false. Can that be the problem? Why is not the label being showed in my page? Can anyone help?
Thanks.
Edit: Here is the full code:
protected void bSubmitChanges_Click1(object sender, EventArgs e)
{
Userfunctions function = new Userfunctions();
List<string> dropList = new List<string>();
List<string> addList = new List<string>();
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
SqlCommand cmd;
con.Open();
string ID = MyGlobals.currentID;
try
{
for (int i = 1; i <= 6; i++)
{
string course;
if ((course = boxCRN(i)) != "")
{
cmd = new SqlCommand("select count (*) from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
cmd = new SqlCommand("select * from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
cmd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
string query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
cmd = new SqlCommand("select * from PrereqTable where CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'", con);
da2 = new SqlDataAdapter(cmd);
dt2 = new DataTable();
da2.Fill(dt2);
List<string> pre = new List<string>();
foreach (DataRow dr5 in dt2.Rows)
{
pre.Add(Convert.ToString(dr5["pCourseCode"]) + Convert.ToString(dr5["pCourseNumber"]));
}
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
c.addPrereq(pre);
string message = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.Text = message;
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
Label1.Visible = true;
Label1.Text = "asdasdasd";
}
}
}
}
}
catch (Exception) { }
for (int i = 0; i < showCourses.Rows.Count; i++)
{
string a = ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue;
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
string courseCode = showCourses.Rows[i].Cells[1].Text, courseNumber = showCourses.Rows[i].Cells[2].Text;
SqlCommand com = new SqlCommand("select * from CourseTable where CourseCode=#courseCode and CourseNumber=#courseNumber", con);
com.Parameters.AddWithValue("courseCode", courseCode);
com.Parameters.AddWithValue("courseNumber", courseNumber);
try
{
SqlDataAdapter da2 = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(c, MyGlobals.student);
MyGlobals.student.dropCourse(reg);
dropList.Add(showCourses.Rows[i].Cells[1].Text + showCourses.Rows[i].Cells[2].Text);
}
catch (Exception) { }
}
}
foreach (string course in dropList)
{
for (int i = 0; i < MyGlobals.student.getRegistered().Count; i++ )
{
if (MyGlobals.student.getRegistered()[i].getCourse().getCode().ToString() + MyGlobals.student.getRegistered()[i].getCourse().getNumber().ToString() == course)
MyGlobals.student.dropCourse(MyGlobals.student.getRegistered()[i]);
}
cmd = new SqlCommand("delete from RegisterTable where StudentID='" + MyGlobals.currentID + "' and CourseCode='" + course.Substring(0, course.Length - 3) + "' and CourseNumber='" + course.Substring(course.Length - 3, 3) + "'", con);
cmd.ExecuteNonQuery();
}
try
{
foreach (string courses in addList)
{
string courseCode = "";
string courseNumber = "";
string term = MyGlobals.currentTerm + " " + MyGlobals.currentYear;
string q = ("select CourseCode from CourseTable where CRN=#courses");
string grade = "";
SqlCommand command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseCode = Convert.ToString(command.ExecuteScalar());
q = ("select CourseNumber from CourseTable where CRN=#courses");
command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseNumber = Convert.ToString(command.ExecuteScalar());
cmd = new SqlCommand("insert into RegisterTable (CourseCode,CourseNumber,Term,StudentID,Grade) values(#courseCode,#courseNumber,#term, #ID,'U')", con);
cmd.Parameters.AddWithValue("#courseCode", courseCode);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#term", term);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
}
}
catch (Exception) { }
con.Close();
Response.Redirect("AddDropClasses.aspx");
}
}
And the registerCourse function:
public string registerCourse(Course course, ref List <string> addList, string crn) {
bool registered = true;
string message ="";
foreach (string s in course.getTime())
{
Userfunctions f = new Userfunctions();
foreach (Register r in this.register) {
if (r.getCourse().getTerm() == MyGlobals.currentTerm.ToString() + " " + MyGlobals.currentYear.ToString() && !f.TimeCheck(s, r.getCourse().getTime()))
{
registered = false;
message = "Time conflict";
}
}
}
if (registered) {
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string id = MyGlobals.currentID;
SqlCommand cmd = new SqlCommand("SELECT count (*) from RegisterTable where CourseCode ='" + course.getCode() +"' and CourseNumber='" + course.getNumber() + "' and Term='" + course.getTerm()+"'" , con);
cmd.Parameters.AddWithValue("#id", id);
int active = Convert.ToInt32(cmd.ExecuteScalar());
if (active >= Convert.ToInt32(course.getCapacity())){
registered = false;
message = "Not enough capacity";
}
if (registered) {
foreach (string s in course.getPrerequisites()) {
if (!hasPassedCourse(s)) {
registered = false;
message = "Prerequisite error";
}
}
}
}
if (registered)
{
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
addList.Add(crn);
}
return message;
}
Remove below line
Response.Redirect("AddDropClasses.aspx");
it will load your page again as new page
When you have Visible="false" set on the control then the control properties may not been instatiated fully.
I would try hiding the control using, errorMessage.Visible=false in the code-behind in your Page_Load instead.

Strange! MySQL update not working without error

The below is my code to create account in my project. The code is working perfect till Response.Write(iduser) but the UPDATE command is not working. No error found using exception but MySQL's record is not updated.
try
{
string pet1 = "admin#testlite.php";
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=newtest;" + "UID=root;" + "PASSWORD=**********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcCommand cmd = new OdbcCommand("Select id_user from awm_accounts where email=?", MyConnection);
cmd.Parameters.Add("#val1", OdbcType.VarChar, 255).Value = pet1;
MyConnection.Open();
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
if (dr.Read())
{
int iduser = Convert.ToInt32(dr[0].ToString());
Account acct = new Account();
acct.Email = username.Text + domain.Text;
acct.MailIncomingLogin = username.Text + domain.Text;
acct.MailIncomingHost = "imap." + DropDownList1.SelectedValue;
acct.MailIncomingPassword = password.Text;
acct.MailIncomingPort = 993;
acct.MailOutgoingHost = "smtp." + DropDownList1.SelectedValue;
acct.MailOutgoingPort = 465;
acct.MailIncomingProtocol = IncomingMailProtocol.Imap4;
acct.MailOutgoingAuthentication = true;
acct.DefaultAccount = false;
acct.IDUser = 1;
integr.CreateUserFromAccount(acct);
Response.Write(iduser);
if (!IsPostBack)
{
cmd = new OdbcCommand("UPDATE awm_accounts SET id_user=? WHERE email=? ", MyConnection);
cmd.Parameters.Add("#tb_nickname", OdbcType.Int, 11).Value = iduser;
cmd.Parameters.Add("#tb_fullname", OdbcType.VarChar, 255).Value = username.Text + domain.Text;
cmd.ExecuteNonQuery();
}
}
MyConnection.Close();
}
catch (Exception exp)
{
Response.Write(exp);
}
I'm not sure about the Response.Write part but I am sure that you create a SQLCommand but never actually execute it.
Did you forget to put a cmd.executeNonScalar() in there?

WebPart in Sharepoint freezes after clicking a linkbutton

I have a user control inside a webpart inside sharepoint that I add some linkbuttons dynamically during runtime. each one when clicked is supposed to download a certain file from the database. however when one of those linkbuttons is clicked, this file is downloaded for once and then i can't click any other buttons or links or even the same one again on this user control and webpart. but i can still click other things outside the user control and webpart. do u have any idea? please tell me which part of the code i can add here if you need to check something. thank you :)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using Microsoft.SharePoint;
using System.Collections.Generic;
using System.Drawing;
public class SearchResult : IComparable
{
private string __nID;
private string __sQuestion;
private string __sAnswer;
private string __nCategoryID;
private string __nPermission;
private string __nLastEdit;
private int __nOccurrence;
public SearchResult()
{
__nOccurrence = 0;
}
public string ID
{
get { return __nID; }
set { __nID = value; }
}
public string Quest
{
get { return __sQuestion; }
set { __sQuestion = value; }
}
public string Answer
{
get { return __sAnswer; }
set { __sAnswer = value; }
}
public string CategoryID
{
get { return __nCategoryID; }
set { __nCategoryID = value; }
}
public string Permission
{
get { return __nPermission; }
set { __nPermission = value; }
}
public string LastEdit
{
get { return __nLastEdit; }
set { __nLastEdit = value; }
}
public int Occurrence
{
get { return __nOccurrence; }
set { __nOccurrence = value; }
}
#region IComparable Members
public int CompareTo(SearchResult res)
{
if (this.Occurrence > res.Occurrence)
return -1;
if (this.Occurrence < res.Occurrence)
return 1;
return 0;
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
SearchResult res = (SearchResult)obj;
if (this.Occurrence > res.Occurrence)
return -1;
if (this.Occurrence < res.Occurrence)
return 1;
return 0;
}
#endregion
}
[System.ComponentModel.Description("Questions")]
public partial class SampleProvider : System.Web.UI.UserControl, SmartPart.IConnectionProviderControl
{
const string FAQConnectionString = "";
private int FileID = 1;
private string CaregoryID = "1";
TextBox tbQuestion;
TextBox tbAnswer;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["CategoryID"] = "0";
LoadTree();
}
System.Web.HttpContext context = System.Web.HttpContext.Current;
string username = context.User.Identity.Name;
LoadQuestions();
}
void LoadQuestions()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = FAQConnectionString;
System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand();
com.Connection = con;
com.CommandText = "SELECT * FROM Questions";
System.Data.SqlClient.SqlDataReader dr;
con.Open();
dr = com.ExecuteReader();
PlaceHolderQuestions.Controls.Clear();
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/><br/><br/>"));
while (dr.Read())
{
if (ViewState["CategoryID"].ToString() != dr[3].ToString())
continue;
Label question = new Label();
question.Text = dr[1].ToString();
question.Font.Name = "Cambria";
question.Font.Bold = true;
question.Font.Size = 11;
question.Width = 500;
Label answer = new Label();
answer.Text = dr[2].ToString();
answer.Font.Name = "Cambria";
answer.Font.Size = 11;
answer.Width = 500;
LinkButton lnkbtnEdit = new LinkButton();
lnkbtnEdit.Click += new EventHandler(lnkbtnEdit_Click);
lnkbtnEdit.CommandArgument = dr[0].ToString();
lnkbtnEdit.CommandName = "edit";
lnkbtnEdit.Text = "Edit";
lnkbtnEdit.Font.Name = "Cambria";
lnkbtnEdit.Font.Size = 11;
lnkbtnEdit.Width = 50;
PlaceHolderQuestions.Controls.Add(question);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
PlaceHolderQuestions.Controls.Add(answer);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = FAQConnectionString;
System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand();
comm.Connection = conn;
/////////////////////////// dr[2] for the QuestionID column at the question table
comm.CommandText = "SELECT * FROM Files WHERE QuestionID = " + dr[0].ToString();
System.Data.SqlClient.SqlDataReader drr;
conn.Open();
drr = comm.ExecuteReader();
while (drr.Read())
{
LinkButton lnkbtnDownloadFile = new LinkButton();
//name of the file ---> drr[2]
lnkbtnDownloadFile.Click += new EventHandler(lnkbtnDownloadFile_Click);
lnkbtnDownloadFile.Text = drr[2].ToString();
lnkbtnDownloadFile.CommandArgument = drr[2].ToString();
PlaceHolderQuestions.Controls.Add(lnkbtnDownloadFile);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
}
ShowLabels(dr[0].ToString());
conn.Close();
PlaceHolderQuestions.Controls.Add(lnkbtnEdit);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<p/>"));
}
con.Close();
}
void EditQuestion(string ID)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = FAQConnectionString;
SqlCommand com = new SqlCommand("SELECT * FROM Questions WHERE ID = '" + ID + "'");
com.Connection = con;
SqlDataReader dr;
con.Open();
string quest="";
string answer = "";
string categoryID = "";
string lastEdit = "";
dr = com.ExecuteReader();
while (dr.Read())
{
quest = dr[1].ToString();
answer = dr[2].ToString();
categoryID = dr[3].ToString();
lastEdit = dr[5].ToString();
}
tbQuestion = new TextBox();
tbAnswer = new TextBox();
tbQuestion.TextMode = TextBoxMode.MultiLine;
tbAnswer.TextMode = TextBoxMode.MultiLine;
tbQuestion.Width = 360;
tbAnswer.Width = 360;
tbQuestion.Text = quest;
tbAnswer.Text = answer;
PlaceHolderQuestions.Controls.Clear();
PlaceHolderQuestions.Controls.Add(tbQuestion);
PlaceHolderQuestions.Controls.Add(tbAnswer);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = FAQConnectionString;
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
/////////////////////////// dr[2] for the QuestionID column at the question table
comm.CommandText = "SELECT * FROM Files WHERE QuestionID = " + ID;
SqlDataReader drr;
conn.Open();
drr = comm.ExecuteReader();
PlaceHolder PlaceHolderFiles = new PlaceHolder();
PlaceHolderQuestions.Controls.Add(PlaceHolderFiles);
// for showing links to the files
while (drr.Read())
{
LinkButton lb = new LinkButton();
//name of the file ---> drr[2]
// lb.Click += new EventHandler(lb_Click);
lb.Text = drr[2].ToString();
PlaceHolderFiles.Controls.Add(lb);
LinkButton lnkbtnDelete = new LinkButton();
// lnkbtnDelete.Click+= new EventHandler(delete_Click);
lnkbtnDelete.CommandArgument = lb.Text;
lnkbtnDelete.Text = "Delete";
lnkbtnDelete.Width = 60;
lnkbtnDelete.Height = 25;
PlaceHolderFiles.Controls.Add(lnkbtnDelete);
PlaceHolderFiles.Controls.Add(new LiteralControl("<br/>"));
}
LinkButton lnkbtnSave = new LinkButton();
lnkbtnSave.Click += new EventHandler(lnkbtnSave_Click);
lnkbtnSave.Text = "Save";
PlaceHolderQuestions.Controls.Add(lnkbtnSave);
conn.Close();
}
void lnkbtnSave_Click(object sender, EventArgs e)
{
if (sender is LinkButton && (sender as LinkButton).CommandName == "save")
SaveQuestion((sender as LinkButton).CommandArgument);
}
private void UpdateQuestionByID(int questionID, string question, string answer, string lastEdited)
{
using (SqlConnection conn = new SqlConnection(FAQConnectionString))
{
conn.Open();
const string QUERY =
#"UPDATE Questions " +
#"SET Question = #Question, Answer = #Answer, LastEdit = #LastEdited " +
#"WHERE ID = #QuestionID";
using (SqlCommand cmd = new SqlCommand(QUERY, conn))
{
cmd.Parameters.AddWithValue("#Question", question);
cmd.Parameters.AddWithValue("#Answer", answer);
cmd.Parameters.AddWithValue("#LastEdited", lastEdited);
cmd.Parameters.AddWithValue("#QuestionID", questionID);
cmd.ExecuteNonQuery();
}
}
}
void SaveQuestion(string ID)
{
UpdateQuestionByID(int.Parse(ID), tbQuestion.Text, tbAnswer.Text, "a");
}
void lnkbtnEdit_Click(object sender, EventArgs e)
{
//if (sender is LinkButton && (sender as LinkButton).CommandName=="edit")
// EditQuestion((sender as LinkButton).CommandArgument);
string id = (sender as LinkButton).CommandArgument.ToString();
Response.Redirect("http://kermit:91/BIMS/Shared%20Documents/EditQuestion.aspx?k="+id);
ViewState["EditID"] = (sender as LinkButton).CommandArgument;
}
void lnkbtnDownloadFile_Click(object sender, EventArgs e)
{
if (sender is LinkButton)
DownloadFile((sender as LinkButton).CommandArgument);
}
private void DownloadFile(string fileName)
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = FAQConnectionString;
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Files WHERE FileName = #ID";
cmd.Parameters.Add("#ID", System.Data.SqlDbType.NVarChar).Value = fileName;
System.Data.SqlClient.SqlDataReader sqlRead = cmd.ExecuteReader();
if (sqlRead.HasRows)
{
while (sqlRead.Read())
{
byte[] fileData = (byte[])sqlRead[3];
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=" + sqlRead[2]);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(fileData);
//Response.Flush();
//Response.End();
Response.Clear();
}
}
con.Close();
sqlRead.Close();
}
protected void lnkbtnAddQuestion_Click(object sender, EventArgs e)
{
}
private void LoadTree()
{
tvCategory.Nodes.Clear();
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = FAQConnectionString;
System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand();
com.Connection = con;
com.CommandText = "SELECT * FROM QuestionCategory WHERE ParentCategoryID = -1";
System.Data.SqlClient.SqlDataReader dr;
con.Open();
dr = com.ExecuteReader();
while (dr.Read())
{
TreeNode tn = new TreeNode();
tn.Text = dr[1].ToString();
tn.Value = dr[0].ToString();
tvCategory.Nodes.Add(tn);
AddChildren(tn);
}
con.Close();
}
private void AddChildren(TreeNode tn)
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = FAQConnectionString;
System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand();
com.Connection = con;
com.CommandText = "SELECT * FROM QuestionCategory WHERE ParentCategoryID = " + tn.Value;
System.Data.SqlClient.SqlDataReader dr;
con.Open();
dr = com.ExecuteReader();
while (dr.Read())
{
TreeNode ctn = new TreeNode();
ctn.Text = dr[1].ToString();
ctn.Value = dr[0].ToString();
tn.ChildNodes.Add(ctn);
AddChildren(ctn);
}
con.Close();
}
protected void tvCategory_SelectedNodeChanged(object sender, EventArgs e)
{
ViewState["CategoryID"] = tvCategory.SelectedValue;
// CaregoryID = tvCategory.SelectedValue;
LoadQuestions();
tvCategory.SelectedNode.Selected = false;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = FAQConnectionString;
SqlDataAdapter adp = new SqlDataAdapter();
DataTable QuestionsTable = new DataTable();
using (SqlConnection oCn = new SqlConnection(FAQConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Questions", oCn);
cmd.CommandType = CommandType.Text;
adp.SelectCommand = cmd;
adp.Fill(QuestionsTable);
}
List<String> wordsSearched = new List<string>();
List<SearchResult> searchResults = new List<SearchResult>();
string[] words = txtbxSearch.Text.ToLower().Split();
//filtering the unnecessary words to prevent searching for
foreach (string s in words)
{
if (s == "to" || s == "the" || s == "is" || s == "are" || s == "in" || s == "of" || s == "on" || s == "with" || s == "are" || s == "it" || s == "this")
continue;
wordsSearched.Add(s);
}
//adding the search result and determine the frequency of occurrence
for (int i = 0; i < QuestionsTable.Rows.Count; i++)
foreach (string w in wordsSearched)
if (QuestionsTable.Rows[i][1].ToString().ToLower().IndexOf(w) > -1 || QuestionsTable.Rows[i][2].ToString().ToLower().IndexOf(w) > -1)
{
SearchResult result = new SearchResult();
result.ID = QuestionsTable.Rows[i][0].ToString();
result.Quest = QuestionsTable.Rows[i][1].ToString();
result.Answer = QuestionsTable.Rows[i][2].ToString();
result.CategoryID = QuestionsTable.Rows[i][3].ToString();
result.Permission = QuestionsTable.Rows[i][4].ToString();
result.LastEdit = QuestionsTable.Rows[i][5].ToString();
result.Occurrence++;
bool isFound = false;
for (int j = 0; j < searchResults.Count; j++)
if (searchResults[j].ID == result.ID)
{
searchResults[j].Occurrence++;
isFound = true;
break;
}
if (!isFound)
searchResults.Add(result);
}
SearchInTags(wordsSearched, searchResults);
searchResults.Sort();
//Session["SearchResults"] = searchResults;
//Response.Redirect("SearchResults.aspx");
LoadSearchResults(searchResults, wordsSearched);
}
void SearchInTags(List<string> words, List<SearchResult> searchResults)
{
foreach (string s in words)
{
using (SqlConnection con = new SqlConnection(FAQConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Questions INNER JOIN QuestionKeyword ON Questions.ID=QuestionKeyword.QuestionID INNER JOIN Keywords ON QuestionKeyword.KeywordID=Keywords.ID WHERE Keywords.Keyword LIKE '%" + s + "%'", con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
SearchResult result = new SearchResult();
result.ID = dr[0].ToString();
result.Quest = dr[1].ToString();
result.Answer = dr[2].ToString();
result.CategoryID = dr[3].ToString();
result.Permission = dr[4].ToString();
result.LastEdit = dr[5].ToString();
result.Occurrence++;
bool isFound = false;
for (int j = 0; j < searchResults.Count; j++)
if (searchResults[j].ID == result.ID)
{
searchResults[j].Occurrence++;
isFound = true;
break;
}
if (!isFound)
searchResults.Add(result);
}
}
}
}
string[] ColorWords(string[] words, string color, List<string> selected)
{
for (int i = 0; i < words.Length; i++)
for(int j=0; j<selected.Count; j++)
if(words[i].ToLower()==selected[j].ToLower())
{
words[i] = "<span style='color: red;'>" + words[i] + "</span>";
break;
}
return words;
}
string ColorText(string text, List<string> selected)
{
int searchFrom = 0;
foreach (string s in selected)
{
int startIndex = text.ToLower().IndexOf(s, searchFrom);
if (startIndex < 0)
continue;
int length = s.Length;
text = text.Insert(startIndex, "<span style='color: red;'>");
text = text.Insert(startIndex + length + 26, "</span>");
}
return text;
}
void LoadSearchResults(List<SearchResult> searchResults, List<string> selected)
{
PlaceHolderQuestions.Controls.Clear();
foreach (SearchResult res in searchResults)
{
Label question = new Label();
question.Text = ColorText(res.Quest, selected);
question.Font.Name = "Cambria";
question.Font.Bold = true;
question.Font.Size = 11;
question.Width = 500;
Label answer = new Label();
answer.Text = ColorText(res.Answer, selected);
answer.Font.Name = "Cambria";
answer.Font.Size = 11;
answer.Width = 500;
HyperLink edit = new HyperLink();
string url = "http://kermit:91/BIMS/Shared%20Documents/EditQuestion.aspx?k=";
url += res.ID;
edit.NavigateUrl = url;
edit.Text = "Edit";
edit.Font.Name = "Cambria";
edit.Font.Size = 11;
edit.Width = 50;
PlaceHolderQuestions.Controls.Add(question);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
PlaceHolderQuestions.Controls.Add(answer);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
SqlConnection conn = new SqlConnection();
conn.ConnectionString = FAQConnectionString;
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
/////////////////////////// dr[2] for the QuestionID column at the question table
comm.CommandText = "SELECT * FROM Files WHERE QuestionID = " + res.ID;
SqlDataReader drr;
conn.Open();
drr = comm.ExecuteReader();
while (drr.Read())
{
LinkButton lb = new LinkButton();
//name of the file ---> drr[2]
// lb.Click += new EventHandler(lb_Click);
lb.Text = drr[2].ToString();
PlaceHolderQuestions.Controls.Add(lb);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
}
ShowLabels(res.ID);
conn.Close();
PlaceHolderQuestions.Controls.Add(edit);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<p/>"));
}
}
void ShowLabels(string questionID)
{
SqlConnection con = new SqlConnection(FAQConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM QuestionKeyword INNER JOIN Keywords ON QuestionKeyword.KeyWordID=Keywords.ID WHERE QuestionID = " + questionID;
cmd.Connection = con;
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
Label lblKeyword = new Label();
lblKeyword.ForeColor = Color.Green;
lblKeyword.Text = dr[4].ToString();
PlaceHolderQuestions.Controls.Add(lblKeyword);
PlaceHolderQuestions.Controls.Add(new LiteralControl(" \t "));
}
con.Close();
PlaceHolderQuestions.Controls.Add(new LiteralControl("<p/>"));
}
#region IConnectionProviderControl Members
public object GetProviderData()
{
return null;
}
public string ProviderMenuLabel
{
get { return "Sends text data to"; }
}
#endregion
}
the weird thing that it works well when i put the same code in an asp.net page!!
Ahmad,
Check out the following link on the MSDN forums, as I believe the situation is similar (if not identical) to what you're describing:
http://social.msdn.microsoft.com/forums/en-US/sharepointdevelopment/thread/107b2c17-07fe-4a15-ad81-dcb31e1e9c84/
A couple of different approaches/solutions are discusssed.
I hope this helps!

Resources