WebPart-Button Click - sharepoint-2007

I have a table called Links.
two stored Procedures called sp_InsertLinks, sp_GetLinks.
I have simple webpart which takes two parameters and adds it the SQL Table call Links.
In The first Interface it displays the list of values from the database and a Button to ADD List.
When I click on the Link it displays next interface, where I can add txtbox for Link Name and Txtbox for Link URL.
And When I submit this The page is loading in the sequence of events of normal sharepoint lifecycle.
And I am unable to add the new links into the page because the button click method never gets fired.
Could any one have a look at this please?
The Code is :
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Text ;
using System.Data ;
using System.Data.SqlClient;
using System.Drawing;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace ContextMenuOptionsUsingJQuery
{
[Guid("7a3a52d4-9ad6-44b2-b96f-852da1a95371")]
public class ContextMenuOptionsUsingJQuery : System.Web.UI.WebControls.WebParts.WebPart
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
string Con_string = string.Empty;
Button btnAddLink;
Button btnAddNewLink;
StringBuilder outputDisplay;
TextBox txtLink;
TextBox txtLinkUrl;
Label lblDisplay = new Label();
public ContextMenuOptionsUsingJQuery()
{
}
protected override void CreateChildControls()
{
try
{
// Getting the Connection
ConnectionMethod();
// Calling the Appropraite Method or stored Procedures
RefreshData();
// Adding a New Link though the button
btnAddLink = new Button();
btnAddLink.Text = "Add Link";
btnAddLink.Click += new EventHandler(btn_AddLink);
//New item
Controls.Add(btnAddLink);
}
catch (Exception e)
{
Label l = new Label();
l.Text = e.StackTrace;
Controls.Add(l);
}
}
// Button Add Link
private void btn_AddLink(Object sender, EventArgs e)
{
Controls.Clear();
btnAddNewLink = new Button();
txtLink = new TextBox();
txtLinkUrl = new TextBox();
Controls.Add(txtLink);
Controls.Add(txtLinkUrl);
btnAddNewLink.Text = "ADD NEW Link";
btnAddNewLink.Click += new EventHandler(btnAddNewLink_Click);
Controls.Add(btnAddNewLink);
}
private void btnAddNewLink_Click(Object sender, EventArgs e)
{
int i;
try
{
ConnectionMethod();
cmd.CommandText = "sp_InsertLinks";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramLinkName = new SqlParameter("#LinkName", SqlDbType.VarChar, 50);
SqlParameter paramLinkUrl = new SqlParameter("#LinkUrl", SqlDbType.VarChar, 50);
paramLinkName.Direction = ParameterDirection.Input;
paramLinkUrl.Direction = ParameterDirection.Input;
paramLinkName.Value = txtLink.Text.ToString();
paramLinkUrl.Value = txtLinkUrl.Text.ToString();
cmd.Parameters.Add(paramLinkUrl);
cmd.Parameters.Add(paramLinkName);
i = cmd.ExecuteNonQuery();
con.Close();
ConnectionMethod();
RefreshData();
}
catch (Exception exp)
{
Label l = new Label();
l.Text = exp.StackTrace;
Controls.Add(l);
}
finally
{
con.Close();
}
}
private void RefreshData()
{
cmd.CommandText = "sp_GetLinks";
cmd.CommandType = CommandType.StoredProcedure;
dr = cmd.ExecuteReader();
outputDisplay = new System.Text.StringBuilder();
outputDisplay.AppendLine("<br/>");
// Fetching the Data from the Datareader object
while (dr.Read())
{
outputDisplay.AppendLine("" + dr[1] + "" + "<br/><br/>");
}
con.Close();
outputDisplay.AppendLine("<br/> <br/>");
lblDisplay.Text = outputDisplay.ToString();
Controls.Add(lblDisplay);
}
// Method to get the Connection
public void ConnectionMethod()
{
con = new SqlConnection();
cmd = new SqlCommand();
Con_string = "Data Source=servername;Initial Catalog=HariVMTest;Integrated Security=True";
con.ConnectionString = Con_string;
con.Open();
cmd.Connection = con;
}
}
}
Thank you
Hari

I would nearly always recommend creating all your controls in CreateChildControls()
Then you should use the Visible property to show and hide the controls as needed.
The code would then look something like this:
public class ContextMenuOptionsUsingJQuery : System.Web.UI.WebControls.WebParts.WebPart {
Button btnAddLink;
Button btnAddNewLink;
protected override void CreateChildControls() {
btnAddLink = new Button();
btnAddLink.Text = "Add Link";
btnAddLink.Click += new EventHandler(btn_AddLink);
Controls.Add(btnAddLink);
btnAddNewLink.Text = "ADD NEW Link";
btnAddNewLink.Click += new EventHandler(btnAddNewLink_Click);
btnAddNewLink.Visible = false;
Controls.Add(btnAddNewLink);
}
private void btn_AddLink(Object sender, EventArgs e) {
btnAddLink.Visible = false;
}
private void btnAddNewLink_Click(Object sender, EventArgs e) {
}
}
If you do it this way, your events will more often than not, fire correctly.

i think you need to just add :
// Adding a New Link though the button
btnAddLink = new Button();
btnAddLink.Text = "Add Link";
btnAddLink.Click += new EventHandler(btn_AddLink);
before connectionmethod in createchildcontrol()
hope this works.

Related

Hi I'm trying to import the captured excel file into table on a button click

enter image description here
Hi I want to export the sheets of excel into a table. I already manage to catch the excel into database. When I click the import button I want to redirect it into a new view and see there the excel values. Any idea how I can do that? I'm using MVC
here is my controller:
public ActionResult Index()
{
Products products = GetProducts();
ViewBag.Message = "";
return View(products);
}
}
[HttpPost]
public ActionResult Index(Products obj)
{
string strDateTime = System.DateTime.Now.ToString("ddMMyyyyHHMMss");
string finalPath = "\\UploadedFile\\" + strDateTime + obj.UploadFile.FileName;
obj.UploadFile.SaveAs(Server.MapPath("~") + finalPath);
obj.FilePath = strDateTime + obj.UploadFile.FileName;
ViewBag.Message = SaveToDB(obj);
Products products = GetProducts();
return View(products);
}
public string SaveToDB(Products obj)
{
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "sp_AddFiles";
cmd.Parameters.AddWithValue("#FileN", obj.FileN);
cmd.Parameters.AddWithValue("#FilePath", obj.FilePath);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Dispose();
con.Close();
return "Saved Successfully";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
// GET: Products
public Products GetProducts()
{
Products products = new Products();
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand("Select * from tblFiles", con);
con.Open();
adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
adapter.Dispose();
cmd.Dispose();
con.Close();
products.lstProducts = new List<Products>();
foreach (DataRow dr in dt.Rows)
{
products.lstProducts.Add(new Products
{
FileN = dr["FileN"].ToString(),
FilePath = dr["FilePath"].ToString()
});
}
}
catch (Exception ex)
{
adapter.Dispose();
cmd.Dispose();
con.Close();
}
if (products == null || products.lstProducts == null || products.lstProducts.Count == 0)
{
products = new Products();
products.lstProducts = new List<Products>();
}
return products;
}
Hi I want to export the sheets of excel into a table. I already manage to catch the excel into database. When I click the import button I want to redirect it into a new view and see there the excel values. Any idea how I can do that? I'm using MVC

Crud operation in asp.net mvc

I have an assignment in ASP.NET MVC and I try to write a crud operation without Entity Framework, but the code is not working correctly.
This is my code:
List<bookModel> books = new List<bookModel>();
SqlConnection con = new SqlConnection("Data Source=DESKTOP-VKO8311;Initial Catalog=BookStore;Integrated Security=True");
string query = "SELECT * FROM books";
SqlCommand command = new SqlCommand(query, con);
try
{
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
books.Add(new bookModel
{
Title = reader["Title of book"].ToString(),
Author = reader["Author"].ToString(),
Price = reader["Price"].ToString()
});
con.Close();
}
}
catch (Exception ex)
{
con.Close();
}
return View(books);
[HttpGet]
public ActionResult NewBook()
{
ViewBag.Title = "Add New Book";
return View();
}
[HttpPost]
public ActionResult NewBook(bookModel model)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-VKO8311;Initial Catalog=BookStore;Integrated Security=True");
string query = "insert into books values(#Ti, #au, #pr)";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.Add("#Ti", System.Data.SqlDbType.VarChar);
command.Parameters["#Ti"].Value = model.Title;
command.Parameters.Add("#au", System.Data.SqlDbType.VarChar);
command.Parameters["#au"].Value = model.author;
command.Parameters.Add("#pr", System.Data.SqlDbType.VarChar);
command.Parameters["#pr"].Value = model.Price;
try
{
con.Open();
command.ExecuteNonQuery();
MessageBox.Show("insert was successful");
return RedirectToAction("books");
}
catch (Exception ex)
{
con.Close();
}
return View();
}
The books.cshtml does not show the result from the database and also the newbook.cshtml does not redirect the create result in the database also.
Any help please?
Your code needs refactoring, but the biggest issue is where you are closing your connection. You don't do it while you're iterating the data reader. Also, take the connection close out of your exception handler. You're better off enclosing it in a using block.
while (reader.Read())
{
books.Add(new bookModel
{
Title = reader["Title of book"].ToString(),
Author = reader["Author"].ToString(),
Price = reader["Price"].ToString()
});
}

How to check if a checkbox was checked in mvc controller

I'm pulling a list of items from table database and checkbox to check and approve each item; however even when I check the item it throws this error message : Please select at least one requested item. What I'm trying to achieve is that the user checks any amount of items in the list and then the status requisition number is updated to 0.
public ActionResult RequisitionList(List<Requisition> postingObj)
{
IssueDAO dbObj = new DAO(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
List<string> reqNumbers = new List<string>();
bool check=false;
foreach (var item in postingObj)
{
if (item.postTrnx)
{
reqNumbers.Add(item.reqNumber);
}
}
if (check == true)
{
dbObj.SetRequisitionStatus0(reqNumbers);
ViewBag.Message = "Approval Successful!";
}
else {
ViewBag.Message = "Please select at least one requested item";
return View(dbObj.GetAllRequest());
}
return View(dbObj.GetAllRequest());
}
public void SetRequisitionStatus0(List<string> reqNumbers)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandText = "requisition_sp_setstatus0";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#reqNumber", SqlDbType.VarChar);
command.Parameters.Add("#approve_date", SqlDbType.DateTime).Value = DateTime.Now;
using (command.Connection = connection)
{
try
{
connection.Open();
foreach (var item in reqNumbers)
{
command.Parameters["#reqNumber"].Value = item;
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
return;
}
public List<Requisition> GetAllRequest()
{
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("getallrequests", connection))
{
command.CommandType = CommandType.StoredProcedure;
List<Requisition> request = new List<Requisition>();
SqlDataReader rdrObj;
connection.Open();
rdrObj = command.ExecuteReader();
while (rdrObj.Read())
{
Requisition requisition = new Requisition();
requisition.reqNumber = rdrObj.GetString(0);
requisition.reqDate = rdrObj.GetDateTime(1);
requisition.items = getRequestItemByRquisition(rdrObj.GetString(0));
request.Add(requisition);
}
rdrObj.Close();
return request;
}
}
}

How display var-binary data to PDF in MVC?

how to display var-binary data to PDF in MVC. can you share anybody how to display var-binary data as PDF in MVC
here i tried in MVC, but not display PDF.
MVC Code:
[HttpPost]
public ActionResult ViewPDF()
{
string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
TempData["Embed"] = string.Format(embed, VirtualPathUtility.ToAbsolute("~/Files/1.pdf"));
return RedirectToAction("Index");
}
here is calling physical path, but i need to read and display var-binary so can anybody share idea?.,
one more thing i displayed var-binary to PDF in asp.net application but unable to display in MVC.
> Asp.net code samples:-
window.open('http://localhost:58158/AspForms/pdf.aspx' + '?id=' + id, '', 'width=800, height=650, top=0, left=250, status=0,toolbar=0');
>
pdf popup page:
protected void Page_Load(object sender, EventArgs e)
{
string embed = "<object data=\"{0}{1}\" type=\"application/pdf\" width=\"800px\" height=\"550px\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
ltEmbed.Text = string.Format(embed, ResolveUrl("~/FileCS.ashx?Id="), Request.QueryString["id"]);
}
FileCS.ashx:-
<%# WebHandler Language="C#" Class="FileCS" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class FileCS : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
#region
int id = int.Parse(context.Request.QueryString["Id"]);
byte[] bytes = { };
string fileName = "", allow = "N";
string constr = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Scan_Pdf_File FROM PWF_InvoiceMain WHERE InvoiceID=#Id and Enabled = 1";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows == true)
{
sdr.Read();
bytes = (byte[])sdr["PDFFile"];
fileName = "Report";
allow = "A";
}
}
con.Close();
}
}
if (allow == "A")
{
context.Response.Buffer = true;
context.Response.Charset = "";
if (context.Request.QueryString["download"] == "1")
{
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
else
{
}
#endregion
}
public bool IsReusable
{
get
{
return false;
}
}
}
but in MVC unable to display var-binary to PDF...
popup view:
#using (Html.BeginForm("DisplayPDF", "Scan", FormMethod.Post))
{
View PDF
}
on Scan controller:-
public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromDB(4);
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(byteArray, 0, byteArray.Length);
pdfStream.Position = 0;
return new FileStreamResult(pdfStream, "application/pdf");
}
private byte[] GetPdfFromDB(int id)
{
#region
byte[] bytes = { };
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Scan_Pdf_File FROM PWF_InvoiceMain WHERE InvoiceID=#Id and Enabled = 1";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows == true)
{
sdr.Read();
bytes = (byte[])sdr["Scan_Pdf_File"];
}
}
con.Close();
}
}
return bytes;
#endregion
}

Please wait screen appearing after the login button

I am trying to implement a "Wait Screen" in my BlackBerry app. The screen is to appear when the user clicks "Login" and it should go away after login has successfully been made. I am calling the screen in the "Login" listener after which I call a methd to fetch data from webs ervice. When the data is fetched, and the new screen is shown, the "Wait Screen" should disappear. However, on clicking login I get Uncaught - RuntimeException after which new screen is displayed with the "Waiting Screen" on top of it. Can somebody help me with this?
public class MessageScreen extends PopupScreen
{
private String message;
public MessageScreen (String message)
{
super( new HorizontalFieldManager(), Field.NON_FOCUSABLE);
this.message = message;
final BitmapField logo = new BitmapField(Bitmap.getBitmapResource( "cycle.gif"));
logo.setSpace( 5, 5 );
add(logo);
RichTextField rtf = new RichTextField(message, Field.FIELD_VCENTER | Field.NON_FOCUSABLE | Field.FIELD_HCENTER);
rtf.setEditable( false );
add(rtf);
}
}
I am calling this in the "Login" click event - button listener.
public void fieldChanged(Field field, int context)
{
// Push appropriate screen depending on which button was clicked
String uname = username.getText();
String pwd = passwd.getText();
if (uname.length() == 0 || pwd.length()==0) {
Dialog.alert("One of the textfield is empty!");
} else {
C0NNECTION_EXTENSION=checkInternetConnection();
if(C0NNECTION_EXTENSION==null)
{
Dialog.alert("Check internet connection and try again");
}
else
{
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen( new MessageScreen("Signing in...") );
}
} );
doLogin(uname, pwd);
}
}
}
private String doLogin(String user_id, String password)
{
String URL ="";
String METHOD_NAME = "ValidateCredentials";
String NAMESPACE = "http://tempuri.org/";
String SOAP_ACTION = NAMESPACE+METHOD_NAME;
SoapObject resultRequestSOAP = null;
HttpConnection httpConn = null;
HttpTransport httpt;
SoapPrimitive response = null;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("username", user_id);
request.addProperty("password", password);
System.out.println("The request is=======" + request.toString());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
httpt = new HttpTransport(URL+C0NNECTION_EXTENSION);
httpt.debug = true;
try
{
httpt.call(SOAP_ACTION, envelope);
response = (SoapPrimitive) envelope.getResponse();
String result = response.toString();
resultRequestSOAP = (SoapObject) envelope.bodyIn;
String[] listResult = split(result, sep);
strResult = listResult[0].toString();
strsessionFirstName = listResult[1].toString();
strsessionLastName = listResult[2].toString();
strsessionPictureUrl = MAINURL + listResult[3].substring(2);
strsessionStatusId = listResult[4].toString();
strsessionStatusMessage = listResult[5].toString();
strsessionLastUpdateTst = listResult[6].toString();
if(strResult.equals("credentialaccepted"))
{
if(checkBox1.getChecked() == true)
{
persistentHashtable.put("username", user_id);
persistentHashtable.put("password", password);
}
Bitmap bitmap = getLiveImage(strsessionPictureUrl, 140, 140);
StatusActivity nextScreen = new StatusActivity();
nextScreen.getUsername(user_id);
nextScreen.getPassword(password);
nextScreen.setPictureUrl(bitmap);
nextScreen.setImage(strsessionPictureUrl);
nextScreen.setFirstName(strsessionFirstName, strsessionLastName, strsessionLastUpdateTst, strsessionStatusMessage);
UiApplication.getUiApplication().pushScreen(nextScreen);
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen( UiApplication.getUiApplication().getActiveScreen() );
}
} );
}
if(strResult.equals("credentialdenied"))
{
Dialog.alert("Invalid login details.");
UiApplication.getUiApplication().pushScreen(new LoginTestScreen() );
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("The exception is IO==" + e.getMessage());
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("The exception xml parser example==="
+ e.getMessage());
}
System.out.println( resultRequestSOAP);
//UiApplication.getUiApplication().pushScreen( UiApplication.getUiApplication().getActiveScreen() );
return response + "";
//UiApplication.getUiApplication().pushScreen(new InfoScreen());
//Open a new Screen
}
Like Eugen said, you should run doLogin() on a background Thread:
final String uname = username.getText();
final String pwd = passwd.getText();
Thread backgroundWorker = new Thread(new Runnable() {
public void run() {
doLogin(uname, pwd);
}
});
backgroundWorker.start();
If you do that, you'll need to use UiApplication.invokeLater() (or another similar technique) to show your screens (back on the main/UI thread). You can't leave the doLogin() method exactly as it originally was, because it makes calls to change the UI. For example, you have a couple calls to directly use pushScreen(), which should not be called (directly) from the background.
This is not ok (from the background):
UiApplication.getUiApplication().pushScreen(nextScreen);
But, this is:
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen(nextScreen);
}
} );
But, also, what is this code supposed to do? :
UiApplication.getUiApplication().pushScreen(nextScreen);
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen( UiApplication.getUiApplication().getActiveScreen() );
}
} );
This doesn't make sense to me. What are you trying to do with those lines of code?
I see only one issue so far - networking in the UI thread. Please put all your networ operations into another Thread.run().
You could also get more detailed error description by:
1) Navigate to home screen
2) Hold alt button and press LGLG on the keyboard
3) Explore showed event log for specific error
try this -
public void fieldChanged(Field field, int context)
{
// Push appropriate screen depending on which button was clicked
String uname = username.getText();
String pwd = passwd.getText();
if (uname.length() == 0 || pwd.length()==0) {
Dialog.alert("One of the textfield is empty!");
} else {
C0NNECTION_EXTENSION=checkInternetConnection();
if(C0NNECTION_EXTENSION==null)
{
Dialog.alert("Check internet connection and try again");
}
else
{
Dialog busyDialog = new Dialog("Signing in...", null, null, 0, Bitmap.getPredefinedBitmap(Bitmap.HOURGLASS));
busyDialog.setEscapeEnabled(false);
synchronized (Application.getEventLock()) {
busyDialog.show();
}
doLogin(uname, pwd);
}
}
}

Resources