Here is my struct definition, function and the portion calling the function.
public struct NewSigningRequest
{
public string SerialNumber;
//public string Requestor;
public string Sponsor;
public string Approver;
public string BusinessJustification;
public byte[] DebugFile;
public string DebugFileName;
public string FirmwareVersion;
public string FirmwareDescription;
public byte[] SmokeTestResult;
public string ProductName;
public string SigningType;
}
static public bool CreateSigningRequest(NewSigningRequest Request)
{
Request = new NewSigningRequest();
bool succeeded = false;
string sqlcmdString = sqlQueryNewSigningRequest;
SqlConnection con = new SqlConnection(connection);
SqlCommand Insertcmd = new SqlCommand(sqlcmdString, con);
SqlParameter SerialNumber = new SqlParameter("#SerialNumber", SqlDbType.NVarChar, 50);
SerialNumber.Value = Request.SerialNumber;
Insertcmd.Parameters.Add(SerialNumber);
SqlParameter Requestor = new SqlParameter("#Requestor", SqlDbType.NVarChar, 20);
Requestor.Value = GetRequestor.GetRequestorAlias();
Insertcmd.Parameters.Add(Requestor);
SqlParameter Sponsor = new SqlParameter("#Sponsor", SqlDbType.NVarChar, 20);
Sponsor.Value = Request.Sponsor;
Insertcmd.Parameters.Add(Sponsor);
SqlParameter BusinessJustification = new SqlParameter("#BusinessJustification", SqlDbType.NVarChar, 2000);
BusinessJustification.Value = Request.BusinessJustification;
Insertcmd.Parameters.Add(BusinessJustification);
SqlParameter DebugFile = new SqlParameter("#DebugFile", SqlDbType.VarBinary, 8000);
DebugFile.Value = Request.DebugFile;
Insertcmd.Parameters.Add(DebugFile);
SqlParameter DebugFileName = new SqlParameter("#DebugFileName", SqlDbType.NVarChar, 100);
DebugFileName.Value = Request.DebugFileName;
Insertcmd.Parameters.Add(DebugFileName);
SqlParameter ProductName = new SqlParameter("#ProductName", SqlDbType.NVarChar, 20);
ProductName.Value = Request.ProductName;
Insertcmd.Parameters.Add(ProductName);
SqlParameter SigningType = new SqlParameter("#SigningType", SqlDbType.NVarChar, 10);
SigningType.Value = Request.SigningType;
Insertcmd.Parameters.Add(SigningType);
SqlParameter FirmwareVersion = new SqlParameter("#FirmwareVersion", SqlDbType.NVarChar, 50);
FirmwareVersion.Value = Request.FirmwareVersion;
Insertcmd.Parameters.Add(FirmwareVersion);
SqlParameter FirmwareDescription = new SqlParameter("#FirmwareDescription", SqlDbType.NVarChar, 250);
FirmwareDescription.Value = Request.FirmwareDescription;
Insertcmd.Parameters.Add(FirmwareDescription);
SqlParameter SmokeTestResult = new SqlParameter("#SmokeTestResult", SqlDbType.VarBinary, 8000);
SmokeTestResult.Value = Request.SmokeTestResult;
Insertcmd.Parameters.Add(SmokeTestResult);
return succeeded;
}
this is how I am trying to call it
NewSigningRequest Request;
byte[] bin;
string FileName;
if (FileUpload.HasFile)
{
bin = new byte[FileUpload.PostedFile.ContentLength];
HttpPostedFile mybin = FileUpload.PostedFile;
FileName = mybin.FileName;
mybin.InputStream.Read(bin, 0, FileUpload.PostedFile.ContentLength);
}
else
{
bin = null;
FileName = "";
}
string NameAlias = #HttpContext.Current.User.Identity.Name;
int index = NameAlias.IndexOf("\\") + 1;
string sAlias = NameAlias.Substring(index);
byte[] SmokeTest;
if (FileUploadSTR.HasFile)
{
SmokeTest = new byte[FileUploadSTR.PostedFile.ContentLength];
HttpPostedFile mySmokeTest = FileUploadSTR.PostedFile;
mySmokeTest.InputStream.Read(SmokeTest, 0, FileUploadSTR.PostedFile.ContentLength);
}
else
{
SmokeTest = null;
}
Request.SerialNumber = TextBoxSerialNumber.Text;
Request.Sponsor = TextBoxSponsor.Text;
Request.BusinessJustification = TextBoxBJ.Text;
if (bin == null)
{
Request.DebugFile = new byte[0];
}
else
{
Request.DebugFile = bin;
}
Request.DebugFileName = FileName;
Request.FirmwareVersion = TextBoxFV.Text;
Request.FirmwareDescription = TextBoxFD.Text;
if (TextBoxSigningType.Text == string.Empty)
{
Request.SigningType = drp2.SelectedValue.ToString();
}
else
{
Request.SigningType = TextBoxSigningType.Text.ToUpper();
}
if (SmokeTest == null)
{
Request.SmokeTestResult = new byte[0];
}
else
{
Request.SmokeTestResult = SmokeTest;
}
SurfaceSignDBAccess.CreateSigningRequest(Request);
upon calling this function, gives error saying that "use of unassigned local variable 'Request'."
What should be the right way to call this function?
NewSigningRequest Request; - is never initialized in the method, before calling
SurfaceSignDBAccess.CreateSigningRequest(Request);
try this:
var request = new NewSigningRequest();// in the first line of code of the second code snippet.
And in the static method, remove the following code.
Request = new NewSigningRequest();
Related
How Can I call the Request Get (Api) from server side.
Here is the Server side
public string GetAllBook()
{
bookAssembly bookassembleur = new bookAssembly();
bookList = bookassembleur.GetBooks();
}
And here is the Api Request
public List<Book> Get()
{
BookAssembly searchallbook = new BookAssembly();
return searchallbook.GetBooks();
bookAssembly bookassembleur = new bookAssembly();
bookList = bookassembleur.GetBooks();
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("ID");
dt.Columns.Add("Title");
dt.Columns.Add("Price");
dt.Columns.Add("Author");
dt.Columns.Add("Qauntite");
dt.Columns.Add("Categorie");
}
foreach (Book book in bookList)
{
DataRow NewRow = dt.NewRow();
NewRow[0] = book.ID;
NewRow[1] = book.Title;
NewRow[2] = book.Price;
NewRow[3] = book.Author;
NewRow[4] = book.Qauntite;
NewRow[5] = book.Categorie.Name;
dt.Rows.Add(NewRow);
}
gvBook.DataSource = dt;
gvBook.DataBind();
return "";
}
i want remove bookList = bookassembleur.GetBooks() ana call api
You have to access it using HttpClient.
e.g.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("<your_api_path>");
var response= client.GetAsync("GetAllBook");
response.Wait();
BookAssembly searchallbook = response.Result;
}
P.S. this is not running code, just an idea.
public string GetAllBook()
{
DataTable dt = new DataTable();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:6735/api/book");
//HTTP GET
var responseTask = client.GetAsync("Book");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<Book[]>();
readTask.Wait();
var Books = readTask.Result;
if (dt.Columns.Count == 0)
{
dt.Columns.Add("ID");
dt.Columns.Add("Title");
dt.Columns.Add("Price");
dt.Columns.Add("Author");
dt.Columns.Add("Qauntite");
dt.Columns.Add("Categorie");
}
foreach (Book book in Books)
{
DataRow NewRow = dt.NewRow();
NewRow[0] = book.ID;
NewRow[1] = book.Title;
NewRow[2] = book.Price;
NewRow[3] = book.Author;
NewRow[4] = book.Qauntite;
NewRow[5] = book.Categorie.Name;
dt.Rows.Add(NewRow);
}
}
}
gvBook.DataSource = dt;
gvBook.DataBind();
return "";
}
I tried to convert java code into cSharp .I struct on how to encode the data so please help me how to do that..
I tried to pass the values directly without encoding then i got the error as
The remote server returned an error: (400) Bad Request.
if i removed the headers then the error is not coming and i placed the break point in the web site the execution sequence is not stopped at the break point
this is my java code
packagename=encodeData("some value");
username=encodeData("some value");
password=encodeData("some value");
hc= new DefaultHttpClient();
get= new HttpGet("http://techpalle.com/skillgun_App.svc/mobile/papers/"+chap_id+"/app");
get.setHeader(PaperActivity.this.getString(R.string.username),username);
get.setHeader(PaperActivity.this.getString(R.string.password),password);
get.setHeader(PaperActivity.this.getString(R.string.packagename),packagename);
Converted csharp code is
string username=null;
string password=null;
string packagename=null;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://localhost:2850/TechpalleNew/Skillgun_App.svc/mobile/chapters/" + "16" + "/app");
wr.Headers["username"] = "username";
wr.Headers["password"] = "password";
wr.Headers["packagename"] = "packagename";
WebResponse resp = wr.GetResponse();
StreamReader read = new StreamReader(resp.GetResponseStream());
string res = read.ReadToEnd();
My website code
namespace ISkillgun_App
{
[ServiceContract]
public interface ISkillgun_App
{
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, UriTemplate = "mobile/chapters/{sub_topic_id}/app")]
List<ChapterNames> Chapters_Names(string sub_topic_id);
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, UriTemplate = "mobile/papers/{chapter_id}/app")]
List<Paper_Ids> Paper_ids(string chapter_id);
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, UriTemplate = "mobile/questions/{paper_id}/app")]
List<Qtions_data> Qtions_data(string paper_id);
}
}
namespace Skillgun_App:ISkillgun_App
{
public List<ChapterNames> Chapters_Names(string sub_topic_id)
Breakppoint {
List<ChapterNames> chptrsdetails = new List<ChapterNames>();
using (SqlConnection cn = new SqlConnection(strConnection))
{
using (SqlCommand cmd = new SqlCommand("skillgun_mobile_app_Qtions_data", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
SqlParameter p1 = new SqlParameter("#type", SqlDbType.VarChar, 20);
SqlParameter p2 = new SqlParameter("#topic_or_paper_id", SqlDbType.Int);
p1.Value = "chapters_data";
p2.Value = sub_topic_id;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add("#username", SqlDbType.VarChar, 40);
cmd.Parameters["#username"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 40);
cmd.Parameters["#password"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#package_name", SqlDbType.VarChar, 50);
cmd.Parameters["#package_name"].Direction = ParameterDirection.Output;
cn.Open();
SqlDataReader drtopics = cmd.ExecuteReader();
while (drtopics.Read())
{
ChapterNames qbsubchapter = new ChapterNames();
qbsubchapter.Qbc_id = (int)drtopics["qbc_id"];
qbsubchapter.Qbc_nameofChapter = drtopics["qbc_nameofChapter"].ToString();
qbsubchapter.Qbc_no_of_papers = (int)drtopics["qbc_no_of_papers"];
qbsubchapter.Qbc_no_of_questions = (int)drtopics["qbc_no_of_questions"];
chptrsdetails.Add(qbsubchapter);
}
drtopics.Close();
cn.Close();
string topic_username = cmd.Parameters["#username"].Value.ToString();
string topic_password = cmd.Parameters["#password"].Value.ToString();
string topic_package_name = cmd.Parameters["#package_name"].Value.ToString();
bool result = check_user(topic_username, topic_password, topic_package_name);
if (result == true)
return chptrsdetails;
else
return null;
}
catch (SqlException ex)
{
return null;
}
finally
{
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
}
}
}
}
public bool check_user(string topic_username, string topic_password, string topic_package_name)
{
string requestedUrl = OperationContext.Current.IncomingMessageHeaders.To.AbsoluteUri;
if (WebOperationContext.Current != null)
{
if (WebOperationContext.Current.IncomingRequest != null)
{
if (WebOperationContext.Current.IncomingRequest.Headers["username"] != null && WebOperationContext.Current.IncomingRequest.Headers["password"] != null && WebOperationContext.Current.IncomingRequest.Headers["packagename"] != null)
{
string username = WebOperationContext.Current.IncomingRequest.Headers["username"];
string pwd = WebOperationContext.Current.IncomingRequest.Headers["password"];
string pckgname = WebOperationContext.Current.IncomingRequest.Headers["packagename"];
bool result = Base64Decode(username, pwd, pckgname, topic_username, topic_password, topic_package_name);
if (result == true)
return true;
else
return false;
}
}
}
return false;
}
For html encoding (you don't specify other), use the static method
HttpUtility.HtmlEncode(string)
http://www.dotnetperls.com/httputility
I have a method that reads data from a database table using SqlDataReader.
i assign data retrieved by SqlDataReader into a List and return it.
when i want to assign the List data from method into the List on Code behind file,
i encounter the following error:
and here is my code
public List<string> displayCustoemrhShipOrder()
{
List<string> drList = new List<string>();
int i = 0;
string sConnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection SqlCOn = new SqlConnection(sConnectionString);
SqlCommand SqlCmd = new SqlCommand();
SqlCmd.Connection = SqlCOn;
SqlCmd.CommandText = "displayCustomerShipOrder";
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCOn.Open();
SqlCmd.Parameters.AddWithValue("ShipOrderID",shipOrderID);
SqlDataReader reader = SqlCmd.ExecuteReader();
while (reader.Read())
{
drList.Insert(i, reader.GetValue(i).ToString());
i++;
}
//reader.Close();
//sqlCon.Close();
reader.Dispose();
SqlCOn.Dispose();
return (drList);
}
code behind code:
protected void Page_Load(object sender, EventArgs e)
{
// string shipOrderID = Session["shipOrderID"].ToString();
// int ID = Convert.ToInt32(shipOrderID);
int ID = 700;
Classes.CustomerShipOrder cuShipOrder = new Classes.CustomerShipOrder(ID);
List<string> ordrList = new List<string>(16);
ordrList= cuShipOrder.displayCustoemrhShipOrder();
cuid.Text = ordrList[0];
Label2.Text = ordrList[1];
Label3.Text = ordrList[2];
Label4.Text = ordrList[3];
Label5.Text = ordrList[4];
Label6.Text = ordrList[5];
Label7.Text = ordrList[6];
Label8.Text = ordrList[7];
Label9.Text = ordrList[8];
Label10.Text = ordrList[9];
Label11.Text = ordrList[10];
stored procedure used :
#ShipOrderID int
as
begin
select * from customerShipOrder where shipOrderID = #ShipOrderID;
end
Hi I am getting an error in supplying parameters to an SSRS report deployed on server in ASP.NET page.
Please refer to the code below and let me know where is the issue?
ReportExecutionService rs = new ReportExecutionService();
string rptURL = System.Configuration.ConfigurationManager.AppSettings["rptURL"].ToString();
string rptPath = System.Configuration.ConfigurationManager.AppSettings["Page1SLScorecardReortForDownload"].ToString();
//Microsoft.Reporting.WebForms.ReportParameter[] paramlist = new Microsoft.Reporting.WebForms.ReportParameter[3];
//paramlist[0] = new Microsoft.Reporting.WebForms.ReportParameter("Week", "2013-05-03");
//paramlist[1] = new Microsoft.Reporting.WebForms.ReportParameter("year", "Fiscal Calendar 2013");
//paramlist[2] = new Microsoft.Reporting.WebForms.ReportParameter("Month", "Fiscal May, 2013");
ParameterValue[] paramlist = new ParameterValue[3];
//Microsoft.Reporting.WebForms.ReportParameter[] paramlist = new Microsoft.Reporting.WebForms.ReportParameter[3];
paramlist[0] = new ParameterValue();
paramlist[0].Name = "Week";
paramlist[0].Value = "2013-05-03";
paramlist[1] = new ParameterValue();
paramlist[1].Name = "year";
paramlist[1].Value = "Fiscal Calendar 2013";
paramlist[2] = new ParameterValue();
paramlist[2].Name = "Month";
paramlist[2].Value = "Fiscal May, 2013";
//ReportViewer1.ServerReport.SetParameters(paramlist);
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = rptURL;
byte[] result = null;
string reportPath = rptPath;
string format = "EXCEL";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string encoding;
string mimeType;
string extension;
ReportingWS.Warning[] warnings = null;
string[] streamIDs = null;
ReportingWS.ExecutionInfo execInfo = new ReportingWS.ExecutionInfo();
ReportingWS.ExecutionHeader execHeader = new ReportingWS.ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
rs.SetExecutionParameters(paramlist, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (Exception ex)
{
//AlnErrorHandler.HandleError(ex);
}
parameters.Add(new ReportParameter("FyId", Convert.ToInt16(objSession.FyId).ToString()));
parameters.Add(new ReportParameter("AccountGroupId", cmbAccountGroup.SelectedValue));
parameters.Add(new ReportParameter("LedgerId", cmbLedgerId.SelectedValue));
rptvwMain.ServerReport.SetParameters(parameters);
Pass Parameters like this....
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!