Excel report unauthorized error link - sql

I am making excel report of my SQL server table records. In Asp page grid view I am fetching required data then this data is downloaded in excel. one column has hyperlink value & I need this hyperlink should only work in Asp page Grid view but after download, it should redirect to a new page where Unauthorized access error will be shown. I am not getting how to show unauthorized error link in excel file hyperlink click.
Here is my code
protected void LnkBtnViewImage_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cs);
LinkButton lnkbtimage = sender as LinkButton;
GridViewRow gvrowreport = lnkbtimage.NamingContainer as GridViewRow;
//int Exhid = Convert.ToInt32(gvrowreport.Cells[1].Text);
string Exhid = ((HiddenField)gvrowreport.Cells[0].FindControl("HiddenField1")).Value;
SqlCommand cmd = new SqlCommand("select ImageName,ImageData from CompanyImage where Edition_Id='" + Session["Edition_ID"].ToString() + "' and Exhibitor_ID=#Exhibitor_ID ", con);
cmd.Parameters.AddWithValue("#Exhibitor_ID", Exhid);
//Select Statement con
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr!=null)
{
dr.Read();
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//string filePath = GridViewLogo.DataKeys[gvrow.RowIndex].Value.ToString();
//if (!Convert.IsDBNull(dr["ImageData"]))
//{
Response.ContentType = "application/vnd.ms-jpg";
//to open file prompt Box open or Save file
Response.AddHeader("content-disposition", "attachment;filename=" + dr["ImageName"].ToString());
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dr["ImageData"]);
Response.End();
//}
//else
//{
// //lblhid.Text = "Image is not uploaded here !!";
// //lblhid.ForeColor = Color.Green;
// //lblhid.Visible = true;
// //// lblhexcelerror.Visible = false;
// //gvrow.Visible = false;
//}
}
else
{
//LinkButton lnkbtn = sender as LinkButton;
//GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//gvrow.Visible = false;
}
con.Close();

With a few specific exceptions (e.g. forms with CSRF tokens) it's usually the case that when you click on a link the server doesn't care how you got there, it receives the request and serves the requested page or resource. It doesn't really know whether the link was contained within an Excel file, or another HTML document, an email etc. That's one of the clever things about hyperlinks, in fact.
Even if what you were suggesting was feasible, there would be nothing to stop a user from copying and pasting it into their browser and accessing it from there.
If you don't want this link to work from your Excel document, and/or you don't want users to be given the link, the simplest thing would be not to include it in the document in the first place.
Also if it's the case that this link is being given to users who shouldn't have access to whatever is shown the link, then simply not giving them the link ("security by obscurity") is not really adequate protection. If that's the situation then you need to think about how access to that link is authorised, no matter where the user acquired the knowledge of it.

use trim in code of reports.
In trim you have to remove "mailto:" while exporting it to the excel

Related

LogIn form, SQL exception

I'm trying to make a simple program that has a log-in part, with a local database just for testing.And i keep getting an error when I try to open the connection to the SQL database.
private void logInButton_Click(object sender, EventArgs e)
{
MainMenu openMainMenu = new MainMenu();
SqlConnection sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30");
sqlcon.Open();
SqlCommand cmd = new SqlCommand("Select * from Table Where username ='" + usernameTextBox.Text + "' and password = '" + passwrodTextBox.Text + "'");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count > 0)
{
openMainMenu.Show();
this.Hide();
}
else
MessageBox.Show("Wrong username or password!");
}
I get the error at sqlcon.Open();, and it is: "An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: An attempt to attach an auto-named database for file C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
Well, the best advice I can give you is to google the error message. Keep in mind that if there is an error message it means that the problem is well known an as such it's a safe bet that someone have encountered it before you and managed to solve it. The first 4 results of this search are on stackoverflow and at least two of them have accepted answers, so I believe a little reasearch would have saved you a long time.
This is the best advice because it streaches far beyond your current problem. I firmly believe that good searching skills is the most important and most powerfull tools of a sotfware developer. I can assure you, no matter how much time you are developing software, almost every exception you get, someone else have already solved and posted the solution somewhere, you only need to find it.
Now, as for the code it self - You have some major problems other then the exception you are asking about:
Concatenating strings into sql statements instead of using parameters expose your code to SQL injection attacks. This is a very serious threat that is extremely easy to fix.
Using insntances of classes that implements the IDisposable interface without properly disposing them may lead to memory leak. Read about the using statement and make it a habit to use it every time it's possible.
Exception handling. Currently, if your database can't be reached, you get an exception and your program crash. You should use a try...catch block anywhere you can't control in code to let your program end gracefuly instead. (Don't ever use try...catch for things you can do in code such as validate user input or checking division by zero - only for things that are beyon your control such as database availability.)
Having said all that, your code should look something like this:
private void logInButton_Click(object sender, EventArgs e)
{
using (var sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|C:\Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30"))
{
sqlcon.Open();
using (var cmd = new SqlCommand("Select 1 from Table Where username = #userName and password = #password"))
{
cmd.Parameters.Add("#userName", SqlDbType.NVarChar).Value = usernameTextBox.Text;
cmd.Parameters.Add("#password", SqlDbType.NVarChar).Value = passwrodTextBox.Text;
using (var dtbl = new DataTable())
{
using (var sda = new SqlDataAdapter(cmd))
{
sda.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
var openMainMenu = new MainMenu();
openMainMenu.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Wrong username or password!");
}
}
}

Get SQL data via listbox

Ok, so what I am trying to do is click one item in a listbox that i have, that listbox gets data from the sql database depending on that the user types into the textbox.
Now when I click that item in the first listbox, I need more info related to that item to show up in the 2nd list box.
When the user enters a name in the textbox, the first 10 in sql show up, now that I have that, I need to click on one of the items and get the 'task' of that client in the next listbox. Task is MATTERS in the database.
I am pretty sure that my code is correct, I get no errors but nothing shows up in the list box.
Here is my code:
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
string item = listBox1.SelectedItem.ToString();
if (listBox1.ContainsFocus)
{
if (item == "")
{
}
else
{
var con2 = Conn.ConnString();
using (SqlConnection myConnection2 = new SqlConnection(con2))
{
string oString2 = "select CLIENTMATTERS.MATTER, CLIENTMATTERS.DESCRIPTION from CLIENTMATTERS join CLIENTCODES on CLIENTMATTERS.CLIENT = CLIENTCODES.CLIENT Where CLIENTCODES.DESCRIPTION = '#code1'";
SqlCommand oCmd = new SqlCommand(oString2, myConnection2);
oCmd.Parameters.AddWithValue("#code1", item);
myConnection2.Open();
oCmd.Connection.Open();
List<string> codelist2 = new List<string>();
using (SqlDataReader oReader2 = oCmd.ExecuteReader())
{
if (oReader2.HasRows)
{
string value = string.Empty;
while (oReader2.Read())
{
codelist2.Add(oReader2["MATTER"].ToString());
}
}
}
this.listBox2.DataSource = codelist2;
}
}
}
}
You need to use BindingList<> instead of List<>.
The List<> doesn't implement the ListChanged event, so the ListBox doesn't get notified when the datasource changes.
In your example it would look like this:
BindingList<string> codelist2 = new BindingList<string>();
For further information take a look at
BindingList on MSDN.

How do I open a file when clicking an ActionLink?

How do I open an existing file on the server when a user clicks an actionlink? The following code works for downloading a file but I want to open a new browser window, or tab, and display the file contents.
public ActionResult Download()
{
return File(#"~\Files\output.txt", "application/text", "blahblahblah.txt");
}
You must add "inline" for a new tab.
byte[] fileBytes = System.IO.File.ReadAllBytes(contentDetailInfo.ContentFilePath);
Response.AppendHeader("Content-Disposition", "inline; filename=" + contentDetailInfo.ContentFileName);
return File(fileBytes, contentDetailInfo.ContentFileMimeType);
The way you're using the File() method is to specify a file name in the third argument, which results in a content-disposition header being sent to the client. This header is what tells a web browser that the response is a file to be saved (and suggests a name to save it). A browser can override this behavior, but that's not controllable from the server.
One thing you can try is to not specify a file name:
return File(#"~\Files\output.txt", "application/text");
The response is still a file, and ultimately it's still up to the browser what to do with it. (Again, not controllable from the server.) Technically there's no such thing as a "file" in HTTP, it's just headers and content in the response. By omitting a suggested file name, the framework in this case may omit the content-disposition header, which is your desired outcome. It's worth testing the result in your browser to see if the header is actually omitted.
Use a target of blank on your link to open it in a new window or tab:
Download File
However, forcing the browser to display the contents is out of your control, as it entirely depends on how the user has configured their browser to deal with files that are application/text.
If you are dealing with text, you can create a view and populate the text on that view, which is then returned to the user as a regular HTML page.
please try this and replace your controller name and action name in html action link
public ActionResult ShowFileInNewTab()
{
using (var client = new WebClient()) //this is to open new webclient with specifice file
{
var buffer = client.DownloadData("~\Files\output.txt");
return File(buffer, "application/text");
}
}
OR
public ActionResult ShowFileInNewTab()
{
var buffer = "~\Files\output.txt"; //bytes form this
return File(buffer, "application/text");
}
this is action link which show in new blank tab
<%=Html.ActionLink("Open File in New Tab", "ShowFileInNewTab","ControllerName", new { target = "_blank" })%>
I canĀ“t vote your answered as is useful, follow dow. Thanks very much !
public FileResult Downloads(string file)
{
string diretorio = Server.MapPath("~/Docs");
var ext = ".pdf";
file = file + extensao;
var arquivo = Path.Combine(diretorio, file);
var contentType = "application/pdf";
using (var client = new WebClient())
{
var buffer = client.DownloadData(arquivo);
return File(buffer, contentType);
}
}

Testing Void in Visual Studio 2010

I have single project(c#) and have the following codes.
Everything is working fine. But I just want to know
how to test it and view the result in Visual Studio 2010.
I am classic asp developer and always use Response.end() to get result. but no idea how to do it in c# project. Thanks.
public static string ApplicationLocationList()
{
GetApplicationLocationListTableAdapter getApplicationLocationListTableAdapter = new GetApplicationLocationListTableAdapter();
DataTable dtgetApplicationLocationListTableAdapter.GetApplicationLocationListData(Library.MovieClass.saveApplicationID);
if (dt.Rows.Count > 0)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dt.Rows.Count; i++)
{
string cityList = dt.Rows[i]["City"].ToString();
string stateList = dt.Rows[i]["State"].ToString();
sb.Append(cityList + "," + stateList + System.Environment.NewLine);
}
return sb.ToString();
}
else
{
return string.Empty;
}
}
Judging by your reference to the Response object, I'm guessing this is an ASP.NET project. If you want to see the contents of sb on the page, you could try the following:
Response.Write(sb.ToString());
Response.Flush();
That should write the contents of the StringBuilder to the Response buffer & the Flush() method should send it down to the client page.
If you want to see only the empty string returned, you could just omit the Write() method & just Flush() the response, which should show you only a blank page after the postback.
I'm assuming that this is an ASP.NET application, in which case you want to use System.Web.HttpApplication.CompleteRequest as an equivalent to Response.End, and Response.Write(sb.ToString()); before the return sb.ToString();.
If it's a console application, then use System.Diagnostics.Debug.WriteLine(sb.ToString()); in the same place.

Unable to open openfileDialog in silverlight

I want to use openfiledialog to upload file,but when I write following code Security exception is fired that is "Dialogs must be user-initiated."
btn_click()
{
OpenFileDialog fileDialog=new OpenFileDialog();
fileDialog.Multiselect = false;
fileDialog.Filter = "All Files|*.*";
bool? retval = fileDialog.ShowDialog();
if (fileDialog.ShowDialog()==false){
Stream strm = fileDialog.File.OpenRead();
byte[] Buffer = new byte[strm.Length];
strm.Read(Buffer, 0, (int)strm.Length);
strm.Dispose();
strm.Close();
Uploadfile file=new Uploadfile();
file.FileName = fileDialog.File.Name;
file.File = Buffer;
po.fileUploadAsync(file);
}
As the exception you're getting states the open file dialog can only be activated from a user initiated action when the application is run in the browser and with restricted trust.
What are you trying to achieve?
The simplest solution is to add a button to your UI that allows the user to control when this process happens.
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt";
if (dlg.ShowDialog() == DialogResult.OK){
using (StreamReader reader = dlg.SelectedFile.OpenText())
// Store file content in 'text' variable
string text = reader.ReadToEnd();
}
}