button_Click event never hit - master-pages

I have a web application utilizing master pages. For some reason, when I add a buttonclick event, the method is never hit. The page goes through the normal page_load events. How do I get my button click event to fire? Previously, This worked just fine, now this is happening in my whole application where the !page.IsPostBack always evaluates false from a button_Click
I have tried adding script Handlers and that doesnt seem to help
in the UI page:
<asp:Button ID="Button1" CssClass="btn btn-primary"
OnClick="putAccoutDetail" runat="server" Text="Save Changes" />
in the CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Authenticated"] == null ||
Session["Authenticated"].ToString() != "true")
{
Response.Redirect("~/Login.aspx");
}
if (!Page.IsPostBack)
{
if (Session["UserID"] != null)
{
UserID = Convert.ToInt32(Session["UserID"]);
getUserData(UserID);
}
}
}
public void putAccoutDetail(object sender, EventArgs e)
{
string statusMsg = string.Empty;
var userInfo = db.UserMasts.FirstOrDefault(s => s.ID == UserID);
if (userInfo != null)
{
userInfo.UserName = txtUserName.Text;
userInfo.MilEmail = txtEmail.Text;
string base64 = Request.Form["imgCropped"];
if (base64.Length > 0)
{
byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
String fileName = Guid.NewGuid().ToString() + ".png";
userInfo.PhotoPath = fileName;
ImagePhoto.ImageUrl = "/Images/Users/" + userInfo.PhotoPath;
using (FileStream stream = new FileStream(Server.MapPath("~/Images/Users/" + fileName), FileMode.Create))
{
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
}
}
}
try
{
dHelper.LogAction("Update User Detail : " + userInfo.UserName);
db.SubmitChanges();
statusMsg = "Successfully Updated";
lblstatusMsg.Text = statusMsg;
lblstatusMsg.Visible = true;
}
catch(Exception ex)
{
statusMsg = "Update Failed";
lblstatusMsg.Text = statusMsg;
lblstatusMsg.Visible = true;
}
}

The issue was that the form had unhandled ASP validators on certain fields. I added a validation group to those and then handled them in the button_Click and all is working

Related

How to change below code from asp.net to razor page

I am new to Razor page but have been working in aspx. This below is my code - please help me convert this to a Razor page:
void Page_Load(object sender, EventArgs e)
{
foreach(string f in Request.Files.AllKeys)
{
HttpPostedFile file = Request.Files[f];
file.SaveAs("C:\\e_data\\WorkPage\\IMS18\\ALBAB_Dynamic\\20008\\Case_Manager\\" + file.FileName);
}
}
I want to change to razor page code.
Here's what I use for uploading a single file and storing the path to the file in a database. It'll explain the bits that Microsoft left out of it's docs (for instance the path to the base directory in .netcore2.2) Note that security is not much of a concern for me as this is a small company intranet... but there's bits in there about getting filename without extension, and you may want to store without the file extension for security reasons (or remove and then add your own extension):
public async Task<IActionResult> OnPostAsync()
{
if (id == null)
{
return NotFound();
}
Kit = await _context.Kits.FirstOrDefaultAsync(m => m.ID == id);
if (Kit == null)
{
return NotFound();
}
if (Request.Form.Files.Count > 0)
{
IFormFile file = Request.Form.Files[0];
string folderName = "UploadedOriginalBOMs";
string OrgBOMRootPath = Path.Combine(AppContext.BaseDirectory, folderName);
if (!Directory.Exists(OrgBOMRootPath))
{
Directory.CreateDirectory(OrgBOMRootPath);
}
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
string fullPath = Path.Combine(OrgBOMRootPath, file.FileName);
// StringBuilder sb = new StringBuilder();
if (file.Length > 0)
{
String cleanFilename = Path.GetFileNameWithoutExtension(file.FileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
Kit.PathToOriginalBOM = "UploadedOriginalBOMs/" + file.FileName;
_context.Kits.Attach(Kit).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
}
else
{
if (!ModelState.IsValid)
{
return Page();
}
}
return RedirectToPage("./Index");
}
You'll notice that you can just use the same forloop as in your .aspx file.

Updating image control in Windows Phone 8

I have a HTML5 web app I can view through my mobile devices.
I have an img control that would download an image using an ashx asp.net handler.
I updated via a timer.
I am trying to port this over to a Windows Phone 8.1 app instead.
The image seems to take ages to update (if at all). This is my code:
long tick = DateTime.Now.Ticks;
BitmapImage bmp =new BitmapImage(new Uri("http://my url/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick));
imgFrame1.Source = bmp;
Is this the correct way?
this is the full code:
private async void LogIn()
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/UserManagement/Login.aspx/Test",
new { username = "", password = "", hubuserid = hubuserid });
var str = await resp.Content.ReadAsStringAsync();
var jsonObj = JsonConvert.DeserializeObject<UserLogIn>(str);
if (jsonObj.d.Success)
{
UpdateConnectionState("Logged In");
}
else
{
UpdateConnectionState("Not Logged In");
}
}
}
public class D
{
public string __type { get; set; }
public bool Success { get; set; }
}
public class UserLogIn
{
public D d { get; set; }
}
private string hubuserid = "";
public string Uptime { get; set; }
private byte ImageIsLoaded = 1;
private async void UpdateTime(int data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try
{
txtInfo.Text = data.ToString();
if (ImageIsLoaded == 1)
{
ImageIsLoaded = 0;
long tick = DateTime.Now.Ticks;
BitmapImage bi = new BitmapImage(new Uri("http://www.informedmotion.co.uk/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick, UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened; }
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
//throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
imgFrame1.Source = (BitmapImage)sender;
}
private void imgFrame1_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
}
private void imgFrame1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
ImageIsLoaded = 1;
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
imgFrame1.ImageFailed += imgFrame1_ImageFailed;
imgFrame1.ImageOpened += imgFrame1_ImageOpened;
ConnectToHub();
}
private void ConnectToHub()
{
proxy.On<int>("broadcastMessage", data =>
{
UpdateTime(data);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
ConnectToHub();
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
LogIn();
}
});
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
ConnectToHub();
};
connection.Reconnected += () =>
{
//LogIn();
UpdateConnectionState("The connection was re-established");
};
}
Windows.UI.Core.CoreDispatcher dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
async void UpdateConnectionState(string state)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try{
txtInfo.Text = state;
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
static HubConnection connection = new HubConnection("http://www.informedmotion.co.uk/");
IHubProxy proxy = connection.CreateHubProxy("ChatHub");
If you're going to download the image, then you probably want to hooked the
Image.DownloadProgress event
Image.ImageOpened event
ImageOpened will fire once the download is complete, so at that moment you can set the .Source to it.
While it is downloading (if it's a huge image) you can either show the previous image or a place holder image (with progress bar maybe?)
BitmapImage bi = new BitmapImage(new Uri("http://www.google.com/myimage.bmp", UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened;
hiddenImage.Source = bi; // we need to set it to an element in the visual tree so the
// events will fire, we're going to use the hiddenImage
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
<!-- myImage is your image that you use to show stuff -->
<!-- hiddenImage is the image we use to fire the event -->
<Image x:Name="myImage"></Image>
<Image x:Name="hiddenImage" Visibility="Collapsed"></Image>

How to remove node id and extension from url in Umbraco

right now I am working on a project, where I have to show a header navigation with url picker data type, for that I took two fields: Text(Text String) & Link(Url Picker).
To get this navigation link this I have done following code:
Default.aspx
<asp:Repeater ID="rptMainNavListing" runat="server" OnItemDataBound="rptMainNavListing_OnItemDataBound">
<HeaderTemplate>
<div class="header_top_links_right">
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink ID="hlLink" runat="server">
</asp:HyperLink>
<asp:Literal ID="ltText" runat="server"></asp:Literal>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</div>
</FooterTemplate>
</asp:Repeater>
Default.aspx.cs
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Reshape.Framework;
using Reshape.Framework.UI;
using Reshape.Framework.Constants;
using umbraco.NodeFactory;
namespace Reshape.UserControls {
public partial class Header : BaseLayout {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
Node currentNode = Common.GetMainNavigationFolder();
var childList = currentNode.Children;
rptMainNavListing.DataSource = currentNode.Children;
rptMainNavListing.DataBind();
}
}
protected void rptMainNavListing_OnItemDataBound(object sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
Node itm = e.Item.DataItem as Node;
if (itm != null) {
Literal ltText = (Literal)e.Item.FindControl("ltText");
HyperLink hlLink = e.Item.FindControl("hlLink") as HyperLink;
if (ltText != null) {
ltText.Text = itm.GetProperty("text").Value;
}
if (hlLink != null) {
hlLink.NavigateUrl = itm.Url;
hlLink.Text = itm.GetProperty("link").Value;
}
}
}
}
}
}
After debugging this code I got url in following form(with id & extension)
False1154/regions.aspxRegions
here id =False1154
extension =regions.aspx
I want url only like "Regions".
In web.config, set the umbracoUseDirectoryUrls value to true.
There is some - rather outdated though - documentation here: http://our.umbraco.org/wiki/install-and-setup/setting-up-umbraco-for-friendly-urls
Change your code to following code....and you will get rid to this problem :-)
if (childList.Count > 0) {
rptMainNavListing.DataSource = childList; ;
rptMainNavListing.DataBind();
}
Repeater Code
protected void rptMainNavListing_OnItemDataBound(object sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
Node itm = e.Item.DataItem as Node;
if (itm != null) {
Literal ltText = (Literal)e.Item.FindControl("ltText");
HyperLink hlLink = e.Item.FindControl("hlLink") as HyperLink;
if (itm.GetProperty(FieldName.LINK) != null && !string.IsNullOrEmpty(itm.GetProperty(FieldName.LINK).Value)) {
hlLink.NavigateUrl = umbraco.library.NiceUrl(Convert.ToInt16(itm.GetProperty(FieldName.LINK).Value));
}
hlLink.Text = itm.GetProperty(FieldName.TEXT).Value;
}
}
}

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);
}
}
}

How to add images in validation summary along with the error message?

I wanna display error message with success image(green tick mark) and failure image(Red warning) in validation summary. how to do this.
and i validation summary i will have to display some text in bold, italics etc. for that i tried to pass string like this.
inValid <b>username</b> or <b>password</b>
But in the page its rendering as it is. it is not showing username and password in bold. is there any way to do that. I am getting this validation error messages in controller and adding this to ModelState.add(error);
The ValidationSummary helper HTML encodes by default all messages. You could write a custom helper which doesn't HTML encode:
public static class HtmlExtensions
{
public static MvcHtmlString MyValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message)
{
var formContext = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
if (formContext == null && htmlHelper.ViewData.ModelState.IsValid)
{
return null;
}
string messageSpan;
if (!string.IsNullOrEmpty(message))
{
TagBuilder spanTag = new TagBuilder("span");
spanTag.InnerHtml = message;
messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine;
}
else
{
messageSpan = null;
}
var htmlSummary = new StringBuilder();
var unorderedList = new TagBuilder("ul");
IEnumerable<ModelState> modelStates = null;
if (excludePropertyErrors)
{
ModelState ms;
htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms);
if (ms != null)
{
modelStates = new ModelState[] { ms };
}
}
else
{
modelStates = htmlHelper.ViewData.ModelState.Values;
}
if (modelStates != null)
{
foreach (ModelState modelState in modelStates)
{
foreach (ModelError modelError in modelState.Errors)
{
var errorText = modelError.ErrorMessage;
if (!String.IsNullOrEmpty(errorText))
{
var listItem = new TagBuilder("li");
listItem.InnerHtml = errorText;
htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));
}
}
}
}
if (htmlSummary.Length == 0)
{
htmlSummary.AppendLine(#"<li style=""display:none""></li>");
}
unorderedList.InnerHtml = htmlSummary.ToString();
var divBuilder = new TagBuilder("div");
divBuilder.AddCssClass((htmlHelper.ViewData.ModelState.IsValid) ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName);
divBuilder.InnerHtml = messageSpan + unorderedList.ToString(TagRenderMode.Normal);
if (formContext != null)
{
// client val summaries need an ID
divBuilder.GenerateId("validationSummary");
formContext.ValidationSummaryId = divBuilder.Attributes["id"];
formContext.ReplaceValidationSummary = !excludePropertyErrors;
}
return MvcHtmlString.Create(divBuilder.ToString(TagRenderMode.Normal));
}
}
Now you have the possibility to use HTML tags in your validation messages:
ModelState.AddModelError("user", "invalid <b>username</b> or <b>password</b>");
and then:
<%= Html.MyValidationSummary(true, null) %>
Obviously by doing this you should ensure that your error messages contain valid HTML structure.
There is no doubt that #Darin Dimitrov answer is the best practice. but as a newbie i am gaining that functionaliy by using ViewBag
Inside Controller
if(true) //All is well and success msg is to be sent
{
ViewBag.Errors = null;
ViewBag.Success = "<b>Login</b> is Successful";
//Redirect
}
else
{
ViewBag.Errors = "<b>Some Error messages</b>";
ViewBag.Success = null;
}
Inside View()
#if(ViewBag.Errors != null)
{
<div class="error">#Html.Raw(#ViewBag.Errors)</div>
}
#if(ViewBag.Success != null)
{
<div class="success">#Html.Raw(#ViewBag.Success)</div>
}
Now the Css
.error { color: red; background-image:error_image.png; }
.success { color:green; background-image : success_image.png; }

Resources