User Control events - asp.net

I have a problem while writting event for ImageUpload User control.
I want to add a event that fire on imagebutton click in this case that green ok button. I write some code for event but it get raised on pageload() and on postback, so it causes a problem --> Image path which is provided for image upload is get clear after image upload but on a page refresh a same image is upload again and again on every page refresh.
User Control Code
public partial class Gallery_Controls_ImgUpload : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }
public string TxtDesc
{
get {return txtimgdesc.Text;}
set { txtimgdesc.Text = value; }
}
public string TxtImgName
{
get { return txtimgname.Text; }
set { txtimgname.Text = value; }
}
public FileUpload ImgUpld
{
get { return ImgUpload; }
//set { ImgUpload = value; }
}
public string ImgAttr
{
get { return ImgUpload.Attributes["onchange"]; }
set { ImgUpload.Attributes["onchange"] = value; }
}
public event EventHandler ImgBtnUpClick;
protected void imgbtnok_Click(object sender,EventArgs e)
{
ImgBtnUpClick(ImgUpload, e);
}
Code for Adding control in page and upload a file
public partial class Gallery_iupload : System.Web.UI.Page
{
ASP.gallery_controls_imgupload_ascx upctrl;
protected void Page_Load(object sender, EventArgs e)
{
upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
protected void Upload(object sender, EventArgs e)
{
TextBox txtbximgname = (TextBox)upctrl.FindControl("txtimgname");
TextBox txtbxdesc = (TextBox)upctrl.FindControl("txtimgdesc");
FileUpload Imgload = (FileUpload)sender;
if (Imgload.HasFile)
try{
Imgload.SaveAs("C:\\Uploads\\" + txtbximgname.Text + ".jpg");
Label1.Text = "File name: " + Imgload.PostedFile.FileName + "<br>" +
Imgload.PostedFile.ContentLength + " kb<br>" +"Content type: " +
Imgload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
}

you have to put a IsPostBack check in your page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{ upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
}

Related

how to stop my FileSystemWatcher in start/stop button

I have a FileSystemWatchers monitoring 1 location in a Start/stop Button, but I canĀ“t manage to stop it, the button works pretty much well as when I click on it, it reads the code when it is off (the text changes to "start Watching") but it does not manage to stop monitoring, also I have tried "watcher.EnableRaisingEvents = false;" but it does not work could you please help me??
using System
using System.ComponentModel
using System.Diagnostics
using System.Drawing
using System.IO
using System.Windows.Forms
namespace Watcher
{
public partial class Form1 : Form
{
private bool isWatching
bool on = true
bool togglelight = true
Timer t = new Timer()
public Form1()
{
InitializeComponent()
}
private void button1_Click(object sender, EventArgs e)
{
if (isWatching)
{
stopWatching()
}
else
{
startWatching()
}
}
private void startWatching()
{
isWatching = true
button1.Text = "Stop Watching"
t.Start()
on = false;
var watcher = new FileSystemWatcher(#"C:\location1")
watcher.NotifyFilter = NotifyFilters.CreationTime
| NotifyFilters.CreationTime
| NotifyFilters.FileName
watcher.Changed += OnChanged
watcher.Error += OnError
watcher.Filter = "*.xlsx"
watcher.IncludeSubdirectories = false
watcher.EnableRaisingEvents = true
private void stopWatching()
{
isWatching = false;
button1.Text = "Start Watching"
button1.BackColor = Color.Gray
t.Enabled = false
t.Stop()
on = true
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
{
return
}
Console.WriteLine(DateTime.Now + " tipo de cambio: " +
e.ChangeType + ". " + e.FullPath)
kNime_Bat(#" C:\Users\BAT\Knime_eSTORE.bat")
Console.WriteLine(DateTime.Now + " se proceso correctamente")
}
private static void OnError(object sender, ErrorEventArgs e) =>
PrintException(e.GetException())
private static void PrintException(Exception ex)
{
if (ex != null)
{
Console.WriteLine($"Message: {ex.Message}")
Console.WriteLine("Stacktrace:")
Console.WriteLine(ex.StackTrace)
Console.WriteLine()
PrintException(ex.InnerException)
}
}
private static void kNime_Bat(string ruta_del_archivoBat_knime)
{
try
{
ProcessStartInfo psi = new ProcessStartInfo()
psi.UseShellExecute = false
psi.CreateNoWindow = true
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = ruta_del_archivoBat_knime
Process.Start(psi)
}
catch (Win32Exception)
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "Start Watching"
t.Interval = 1000
t.Tick += new EventHandler(t_Tick)
}
private void t_Tick(object sender, EventArgs e)
{
if (togglelight)
{
button1.BackColor = Color.DarkBlue
togglelight = false
}
else
{
button1.BackColor = Color.Gray
togglelight = true
}
}
}
}
I have tried watcher.EnableRaisingEvents = false in Stopwatching event but it seems like if it works in a new instance as it does not stop the watcher, how I know? because after I click on "stop" I make a new change in the watched folder and I get an answer in OnChanged event.

Using CefBrowser.ExecuteScriptAsync with BindObjectAsync Not Working

I am using the below code to try to bind a c# class that has been registered but do not see "dwgData" anywhere under Scope when debugging the webpage. What would dwgData be bound to?
private void ChromiumBrowserForm_Load(object sender, EventArgs e)
{
CefSettings settings = new CefSettings();
ChromiumWebBrowser browser = new ChromiumWebBrowser("http://localhost:3000");
this.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browser.JavascriptObjectRepository.Register("dwgData", new DwgData(), true, null);
browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged;
browser.LoadingStateChanged += Browser_LoadingStateChanged;
}
private async void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
if (e.IsLoading == false)
{
await Task.Run(() => browser.ExecuteScriptAsync("CefSharp.BindObjectAsync(\"dwgData\");"));
}
}
private void Browser_IsBrowserInitializedChanged(object sender, EventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
if (browser.IsBrowserInitialized)
{
browser.ShowDevTools();
}
}
public class DwgData
{
public void showMessage()
{
MessageBox.Show("HELLO FROM JS");
}
}

ASP.NET Page with multiple custom controls implementing IPostBackEventHandler

I am having an ASP.Net Page which contains multiple controls which implement the IPostBackEventHandler interface. The SIMPLIFIED VERSION of the code is given below:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Custom Control
MyTextBox mytxt = new MyTextBox();
mytxt.ID = "mytxt";
mytxt.TextChange += mytxt_TextChange;
this.Form.Controls.Add(mytxt);
//Custom Control
MyButton mybtn = new MyButton();
mybtn.ID = "mybtn";
mybtn.Click += mybtn_Click;
this.Form.Controls.Add(mybtn);
}
void mybtn_Click(object sender, EventArgs e)
{
Response.Write("mybtn_Click");
}
void mytxt_TextChange(object sender, EventArgs e)
{
Response.Write("mytxt_TextChange");
}
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class MyTextBox : Control, IPostBackEventHandler
{
public event EventHandler TextChange;
protected virtual void OnTextChange(EventArgs e)
{
if (TextChange != null)
{
TextChange(this, e);
}
}
public void RaisePostBackEvent(string eventArgument)
{
OnTextChange(new EventArgs());
}
protected override void Render(HtmlTextWriter output)
{
output.Write("<input type='text' id='" + ID + "' name='" + ID + "' onchange='__doPostBack('" + ID + "','')' />");
}
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class MyButton : Control, IPostBackEventHandler
{
public event EventHandler Click;
protected virtual void OnClick(EventArgs e)
{
if (Click != null)
{
Click(this, e);
}
}
public void RaisePostBackEvent(string eventArgument)
{
OnClick(new EventArgs());
}
protected override void Render(HtmlTextWriter output)
{
output.Write("<input type='button' id='" + ID + "' name='" + ID + "' value='Click Me' onclick='__doPostBack('" + ID + "','')' />");
}
}
There are 2 custom controls - MyTextBox & MyButton implementing the IPostBackEventHandler interface. MyTextBox has the TextChange event and MyButton has the Click event.
If I keep only one control on the page (MyTextBox or MyButton) - the events fire property. But with both controls on the page the MyTextBox TextChange event is getting fired even after clicking the MyButton. The MyButton Click event does not get fired when the MyTextBox is on the page.
I have tried multiple things before posting it here. Thanks in advance for the help.
The cause of the problem is that you need to call __doPostBack method with UniqueID of the control. This is vital. Also, basically server controls render ClientID as ID of the element and UniqueID as element name. So if you update your render methods to the following everything will work:
TextBox:
output.Write("<input type='text' id='" + this.ClientID + "' name='" + this.UniqueID + "' onchange='__doPostBack('" + this.UniqueID + "','')' />");
Button:
output.Write("<input type='button' id='" + this.ClientID + "' name='" + this.UniqueID + "' value='Click Me' onclick='__doPostBack('" + this.UniqueID + "','')' />");
EDIT:
Using UniqueID seems really didn't help to resolve your problem. I don't know the cause of the problem, but I tried to overwrite your custom text box using base WebControl class and this helps to resolve problem. So, you can try to go with this implementation.
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class MyTextBox : WebControl, IPostBackEventHandler
{
public event EventHandler TextChange;
protected virtual void OnTextChange(EventArgs e)
{
if (TextChange != null)
{
TextChange(this, e);
}
}
public void RaisePostBackEvent(string eventArgument)
{
OnTextChange(new EventArgs());
}
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Input;
}
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute(HtmlTextWriterAttribute.Onchange, Page.ClientScript.GetPostBackEventReference(this, string.Empty));
writer.AddAttribute("onkeypress", "if (WebForm_TextBoxKeyHandler(event) == false) return false;");
writer.AddAttribute(HtmlTextWriterAttribute.Type, "text");
}
}

Passing DataKeys between pages

Using a GridView on the default page and want to show details of the row selected on another page. The code for capturing and sending the datakey is -
protected void SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
Response.Redirect("InvoicePage.aspx? EntityID= " + GridView1.DataKeys[index].Value.ToString());
}
And the code for retrieving the value is -
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["EntityID"];
}
My problem is that the id variable is a null on the receiving page. What am I missing?
Your URL should look something like this: InvoicePage.aspx?EntityID=", No space before or after EntityID
By The way Remove the white space : aspx?<>*EntityID<>*=
protected void SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
string id = GridView1.DataKeys[index].Value.ToString();
Response.Redirect("InvoicePage.aspx?EntityID="+id);
}
Try to add :
private string _EntityId;
//To check if value pass on query string
//but this is not really required if you want
public string EntityId
{
get
{
if (Request.QueryString["EntityID"] != null)
{
try
{
_EntityId = Convert.ToString(Request.QueryString["EntityID"].ToString());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
else
{
_EntityId="0";
}
return _EntityId;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Request.QueryString["EntityID"].ToString();
string id = EntityId;
}
Regads

Login page fault

I had login Page and it worked well but remember me check box didn't work well and I couldn't know where the error please anyone help me this is my code
public partial class _Default : System.Web.UI.Page
{
public TextBox Usertxt,Passwordtxt;
protected void Page_Load(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
if (!IsPostBack)
{
if (Request.Cookies["Mycookie"] != null)
{
HttpCookie Cookie = Request.Cookies.Get("Mycookie");
Usertxt.Text=Cookie.Values["UserName"];
Passwordtxt.Text=Cookie.Values["Password"];
}
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
Literal LBL;
LBL = (Literal)Login1.FindControl("FailureText");
if (FormsAuthentication.Authenticate(Usertxt.Text, Passwordtxt.Text))
{
Response.Redirect("");
}
else
{
Login1.FindControl("FailureText");
LBL.Text = "error ocurred";
}
}
}
Thank you more I got the answer and this the right code
public partial class _Default : System.Web.UI.Page
{
public TextBox Usertxt, Passwordtxt;
public Literal LBL;
public CheckBox CHB;
protected void Page_Load(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
if (!IsPostBack)
{
if (Request.Cookies["MyCookie"] != null)
{
HttpCookie Cookie = Request.Cookies.Get("MyCookie");
Usertxt.Text = Cookie.Values["UserName"];
Passwordtxt.Text = Cookie.Values["Password"];
}
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
CHB = (CheckBox)Login1.FindControl("RememberMe");
LBL = (Literal)Login1.FindControl("FailureText");
HttpCookie MyCookie = new HttpCookie("MyCookie");
bool IsRememberme = CHB.Checked;
if (IsRememberme)
{
MyCookie.Values.Add("UserName", Usertxt.Text);
MyCookie.Values.Add("Password", Passwordtxt.Text);
MyCookie.Expires = DateTime.Now.AddDays(15);
}
else
{
MyCookie.Values.Add("UserName", string.Empty);
MyCookie.Values.Add("Password", string.Empty);
MyCookie.Expires = DateTime.Now.AddDays(5);
}
Response.Cookies.Add(MyCookie);
if (FormsAuthentication.Authenticate(Usertxt.Text, Passwordtxt.Text))
{
Response.Redirect("");
}
else
{
Login1.FindControl("FailureText");
LBL.Text = "error ocurred";
}
}
}

Resources