How can i use file upload control in dnn module programming? - c#

I want to use file upload control in dnn module programming.
I know there is DnnFilePicker in dnn, but I want a simple code that each user can upload a file and after that can display, edit and delete it.
There is this code but is not complete.
<%# Register TagPrefix="dnn" Assembly="DotNetNuke.Web" Namespace="DotNetNuke.Web.UI.WebControls" %>
<dnn:DnnFilePicker runat="server" ShowFolders="false" ID="fpUserFiles" FileFilter="pdf,gif,jpg" />
In Page_Load event, set the folder:
// Limit filepath to user's folder
fpUserFiles.FilePath = FolderManager.Instance.GetUserFolder(User).FolderPath;
what should i do?

If you have some sort of Save event on your module view, you simply get the FileId of the file that was selected by the user to save it in the database:
protected void btnSubmit_Click(object sender, EventArgs e)
{
ModelData model = new ModelData {
FileId = fpUserFiles.FileID
};
// TODO: Save your model data
}
In your Page_Load event, you can also load model data (if user is editing an existing model) by setting the fileID on the File Picker. That will pre-select the file in the picker control.
fpUserFiles.FileID = model.FileId
To use the fileId in another module view, you can get it from your model data and get the attributes of the file like this example:
FileInfo fi = (FileInfo)FileManager.Instance.GetFile(model.FileId);
if (fi != null)
{
pic.ImageUrl = "/" + _currentPortal.HomeDirectory + "/" + fi.RelativePath;
}

With this code my problem is resolved.
each user can upload its files in its folder.
protected void Page_Load(object sender, EventArgs e)
{
username = UserController.GetCurrentUserInfo().Username.ToString();
}
protected void Button1_Click1(object sender, System.EventArgs e)
{
var folder = Server.MapPath("~/uploads/Company/" + username);
if (this.FileUpload1.HasFile)
{
Directory.CreateDirectory(folder);
this.FileUpload1.SaveAs(folder + "/" + this.FileUpload1.FileName);
}
}

Related

how to get list of uploaded files by ajaxfileupload

i'm using ajaxfileupload in my asp.net project
i to get list of uploaded files and save them in database
but i don't know how i can get which files are uploading when i press on upload button
protected void AjaxFileUpload1_UploadComplete1(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string filePath = MapPath("~/images/") + System.IO.Path.GetFileName(e.FileName);
AjaxFileUpload1.SaveAs(filePath);
}

Using textbox to gather user's destination path for exporting a CSV in C# Windows application?

I'm looking for an option that allows a user to input their destination folder (Usually copy/Paste) into a text box on a Windows Application, and append the file's name with a specific name. However, I'm stuck as to how to accomplish this.
//Exporting to CSV.
string folderPath = MessageBox.Show(textBox1_TextChanged);
File.WriteAllText(folderPath + "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv", csv);
So it can look like: C:/DIR_9132017.csv, or Documents/DIR_9132017.csv, depending on what the user inputs into the textbox. I have nothing in my textbox code section at the moment, if that also gives a clearer picture about the situation.
Any help will be greatly appreciated. Thank you!
You can either use FolderBrowserDialog or can just copy/paste the path and create the directory.
Using FolderBrowserDialog
Step1 : Create Browse button (so that the user can choose the directory)
Step2 : Create Export button (Place the code to write the file here)
private void browseButton_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
var folderPath = folderBrowserDialog1.SelectedPath;
textBox1.Text = folderPath;
}
}
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
Using Copy/Paste
Step1 : Create Export button (User copy pastes the path. System create the directory and writes the file)
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
You would use a FolderBrowserDialog for that. After adding it to your form, you can use it like this:
public void ChooseFolder()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
folderPath = folderBrowserDialog1.SelectedPath;
}
}
Source: https://msdn.microsoft.com/en-us/library/aa984305(v=vs.71).aspx
You haven't specified whether it's WinForms or WPF, so I'm using WPF, but is should be the same in WinForms.
To select the folder, you could use FolderBrowseDialog as follows. This code should be placed inside a button or some other similar control's Click event.
if (folderBrowse.ShowDialog() == DialogResult.OK)
{
txtPath.Text = folderBrowse.SelectedPath;
}
txtPath being a TextBox your selected path displayed in. You can substitute it with a simple string variable if you don't want to use a TextBox.
And if you want the user to be able to drag-drop a folder into a TextBox, you can create a TextBox control, and in it's PreviewDragOver and Drop events, you can do the following.
private void txtPath_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
private void txtPath_Drop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files != null && files.Length != 0)
txtPath.Text = files[0];
}
Using both above in combination user has the ability to either select the folder he/she wants by clicking a button, drag-and-drop a folder into the TextBox, or copy-paste the folder path into the TextBox.

How to call a function from another .aspx page before the page_load() in asp.net?

I have a aspx page called test.aspx that inherits a master page.The master page has usercontrol file called lcont.ascx which has a treeview whose node is populated with data from database and a contentpalceholder.
The contentplaceholder is where i want to display data from database according to the treenode clicked and so has a Datalist defined within it.Its corresponding .cs file gives the sqlconnection and query to display data in page_load.
So whenever I click the treenode in the test.aspx , the page_load of its corresponding .cs file is called.But what i want is to call .cs file of usercontrol file lcont.ascx so that i can pass the id to query in .cs file of test.aspx.cs.
Is it possible to call function from another page before page_load?
Or is it possible to go to .cs file of another file before going through its own .cs file?
Here is the code from lcont.ascx.cs
protected void my_tv_SelectedNodeChanged(object sender, EventArgs e)
{
TreeView tv = sender as TreeView;
var selectedN = tv.SelectedNode;
if (selectedN.Parent != null)
{
var id = tv.SelectedNode.Value;
var name = tv.SelectedNode.Text;
//Session["mySvar"] = id;
ScriptManager.RegisterStartupScript(this, this.GetType(), "nething", "show("+id+")", true);
}
else
{
//Response.Redirect("test.aspx");
}
}
I want to call this function before the page_load of test.aspx.cs file.
The code of test.aspx.cs file is
protected void Page_Load(object sender, EventArgs e)
{
display();
}
public void display()
{
string str = hdn.Value;
slbl.Text = "value is" + str;
//var a = Session["mySvar"];
var a = 2;
sq.connection();
SqlCommand cmd = new SqlCommand("select * from sub_catTbl where sid='" + a + "' ", sq.con);
SqlDataReader sd = cmd.ExecuteReader();
mydatalist.DataSource = sd;
mydatalist.DataBind();
sq.con.Dispose();
sq.con.Close();
}
I need to call the function before this page_load call so that i can give sid = "variable value that i obtain after clicking the treenode that is available in lcont.ashx.cs"
Partially answered here, but this answer is actually better: You shouldn't call an event from another page.
Either create a class that handles your TreeWiew events(to access it from another context), or rethink your application.
using VB.net , on Page Initializing
Private Sub _Default_Init(sender As Object, e As EventArgs) Handles Me.Init
display()
End Sub
Here is the C# Code :
protected void Page_Init(object sender, EventArgs e)
{
display();
}

Not getting value in Viewstate in asp.net using C#?

I am using a asyncfileupload control to upload a file there i am taking the path in a view state like this:
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = System.IO.Path.GetFileName(e.FileName);
string dir = Server.MapPath("upload_eng/");
string path = Path.Combine(dir, name);
ViewState["path"] = path;
engcertfupld.SaveAs(path);
}
Now when i am trying to save that path in a buttonclick event i am not getting the value of viewstate:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string filepath = ViewState["path"].ToString(); // GETTING NULL in filepath
}
In this filepath i am getting null actually i am getting error NULL REFERENCE EXCEPTION
What can I do now?
Put the Path value in the Session object instead of the ViewState, like this:
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
....
string path = Path.Combine(dir, name);
Session["path"] = path;
}
Then in the Button Click:
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (Session["path"] != null)
{
string filepath = (string) Session["path"];
}
}
I guess the upload process is not a "real" postback, so the ViewState will not be refreshed client side and won't contain the path upon click on btnUpdate_Click
What you should do is use the OnClientUploadComplete client-side event to retrieve the uploaded file name, and store it in a HiddenField that will be posted on the server on btnUpdate_Click.
Here is a complete example where the uploaded file name is used to display an uploaded image without post-back :
http://www.aspsnippets.com/Articles/Display-image-after-upload-without-page-refresh-or-postback-using-ASP.Net-AsyncFileUpload-Control.aspx

urlrewriting in asp.net button click

Hi all I have seen many articles on url rewriting but I didn't find any as per my requirement. Assume I have two pages Default.aspx and Default1.aspx.. On initial load I would like to re write my Default.aspx to some thing like urlrewrite\dummy.aspx and on my Default.aspx I will have a button when I click on this I am going to redirect to Default1.aspx I would like to rewrite this to urlrewrite\dummy1.aspx
I just post the sample rewrites but if there is any better way of redirecting can you please help me..
Also what is the best way to rewrite all pages if I have some 20-50 pages
my global.asax file
<%# Application Language="C#" %>
<%# Import Namespace="System.Web" %>
<%# Import Namespace="System.Web.Routing" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routeCollection)
{
string root = Server.MapPath("~");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(root);
System.IO.FileInfo[] files = info.GetFiles("*.aspx", System.IO.SearchOption.AllDirectories);
foreach (System.IO.FileInfo fi in files)
{
string pageName = fi.FullName.Replace(root, "~/").Replace("\\", "/");
routeCollection.MapPageRoute(fi.Name + "Route", fi.Name, pageName);
}
routeCollection.MapPageRoute("DummyRouteName1", "Dummy", "~/Default2.aspx");
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>
You can add routes in your Global.asax file on application start:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}
private void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("DummyRouteName", "Dummy", "~/Default.aspx");
....
}
Usage:
Response.Redirect("~/Dummy");
In url you will see: (server)/Dummy
Edit:
here is how to automatically add routes:
// Get root directory
string root = Server.MapPath("~");
DirectoryInfo info = new DirectoryInfo(root);
// Get all aspx files
FileInfo[] files = info.GetFiles("*.aspx", SearchOption.AllDirectories);
foreach (FileInfo fi in files)
{
// Get relative path
string pageName = fi.FullName.Replace(root, "~/").Replace("\\", "/");
// Add route
routes.MapPageRoute(fi.Name + "Route", fi.Name.Replace(".aspx", ""), pageName);
}
I assume that you got that rewriting part covered and only problem is postback, you can set postback to "friendly" URL by seting form action, like this :
Page.Form.Action = Page.Request.RawUrl;

Categories