i have aspx webform that contains search box and button like this
In code behind NT search method called using web method like this
[WebMethod]
public static void GetNT(string NTID)
{
try
{
myService.myServiceClient me = new myService.myServiceClient();
DataSet dsResult = me.InfobyNt(NTID);
ware1 _ware1 = new ware1();
_ware1.AssignValues(dsResult);
}
catch (Exception ex)
{
ex.ToString();
}
}
i had result on dataset and passed to assignvalues method, there i bind values like this
protected void AssignValues(DataSet dsResult1)
{
try
{
if (dsResult1 != null && dsResult1.Tables[0].Columns.Count > 1)
{
Response.Write(dsResult1.Tables[0].Rows[0]["EMPNAME"].ToString());
// foreach(var datas in dsResult.Tables[0].Rows)
//{
string name = dsResult1.Tables[0].Rows[0]["EMPNAME"].ToString();
txtFname.Text = name.ToString();
txtEmilSgs.Text = Convert.ToString(dsResult1.Tables[0].Rows[0]["EMAILID"]);
txtPrgSgs.Text = Convert.ToString(dsResult1.Tables[0].Rows[0]["PROGNAME"]);
txtMname.Text = Convert.ToString(dsResult1.Tables[0].Rows[0]["MANAGERNAME"]);
//}
}
else
{
Response.Write("<script>alert('fail')</script>");
btnSgsLoad.Text = "Can't find NT ID";
}
}
catch (Exception ex)
{
ex.ToString();
}
}
while binding data from dataset an error thrown like this
can somebody help me how to bind dataset values into asp:textbox
dsResult1.Tables[0].Columns.Count > 1 replace this with dsResult1.Tables[0].Rows.Count > 1 because there is no reason to count columns of dataset table, probably your dataset is not null but tables in your dataset is null check if your dataset has tables and rows as per your expectation otherwise you will get the same error. and
string name = dsResult1.Tables[0].Rows[0]["EMPNAME"].ToString();
this line is getting null value to "name" string that's the reason behind this error.
Check you dataset is full fill with all records
Related
I am trying to update let's say 3 items simultaneously in recyclerview after fetching certain values from the firebase database. The below method iterates through ArrayList itemname thrice and with each value, it calls the method SecurityAlertSensor(itemname).
Within this method for each iteration, the respective item in recycler view shall change. Like if the id fetched from the SQLite DB is 1 then the 1st item of recycler view will be updated and on the next iteration, if the id is 2 then the 2nd item will be updated similarly for the 3rd item.
But with the below code only the last of the three items of the recycler view is updating the first two are not working.
for (int i=0; i<itemname.size(); i++) {
if (isOnline()) {
SecurityAlertSensor(itemname.get(i));
}
else if(!isOnline())
Toast.makeText(getApplicationContext(), "Update Failed!", Toast.LENGTH_SHORT).show();
}
This method fetches the value from Firebase DB on each iteration and if the value is "1" then it calls notifyItemChanged(position) to update the specific item in recyclerview.
private void SecurityAlertSensor(final String email) {
sec_ref2 = sec_ref1.child(email);
sec_ref2.addValueEventListener(new ValueEventListener() {
int id;
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
String value = dataSnapshot.getValue(String.class);
if (value != null)
{
if (value.contains("0") || value.contains("1"))
{
Toast.makeText(Security.this, value, Toast.LENGTH_SHORT).show();
String[] tokens = value.split(",");
power_state = tokens[0];
ContentValues values = new ContentValues();
values.put(SecurityDatabaseContract.UserDatabase2.SEC_NAME_COL4, tokens[0]);
values.put(SecurityDatabaseContract.UserDatabase2.SEC_NAME_COL5, tokens[1]);
SecDB.update(SecurityDatabaseContract.UserDatabase2.TABLE_NAME2, values, "address='" + email + "'", null);
String query = "SELECT id FROM sec_table WHERE address='"+email+"'";
Cursor c1 = SecDB.rawQuery(query,null);
if (c1 != null && c1.getCount() != 0)
{
while (c1.moveToNext()) {
id = c1.getInt(c1.getColumnIndex("id"));
}
c1.close();
}
if (tokens[1].equals("1")) {
alert_position = id;
userAdapter.notifyItemChanged(alert_position);
}
}
sec_ref2.removeEventListener(this);
}
else
Toast.makeText(Security.this, "Device Not Found!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getApplicationContext(), "Not Found!", Toast.LENGTH_LONG).show(); // Failed to read value
}
});
}
Inside the Recyclerview Adapter class onBindViewHolder method. This gets called each time the notifyItemChanged(position) is instantiated inside the main class.
public void onBindViewHolder(#NonNull final UserViewHolder holder, final int position) {
if(position == Security.alert_position) {
holder.state.setText("< Activated >");
holder.state.setTextColor(Color.RED);
holder.cards.setBackgroundColor(0x33FF0000);
}
}
Your problem is here in onBindViewHolder():
if(position == Security.alert_position) {
You rely on the value of Security.alert_position being set to the item position on each iteration. I'm guessing that each call to notifyItemChanged() does not produce an immediate call to onBindViewHolder(), but that the calls made to onBindViewHolder() are asynchronous and happen later. By then Security.alert_position has already been set to the third value so that each time you enter onBindViewHolder(), the value of Security.alert_position is the last value that you set.
You could add some debug logging to verify my assumption. Generally your architecture is not good, as you are relying on the state stored in one place when doing something in another place.
When a SignalR update comes through to our page to update our modal, our item names change and our scripts seem to break.
Brief overview: Our SignalR update gets sent to the website fine, but the data itself has an invalid name.
Once updated, our items refresh with malformed names. Our names shouldn't be updated by SignalR in the first place, and I can't seem to find any references to it in our code.
Closing the modal, our Highcharts and Angular scripts throw console errors.
Server-side code:
public partial class Device
{
if (device != null)
{
if ((Enumerables.DeviceType)device.Type == Enumerables.DeviceType.Store)
SignalrClient.UpdateStore(device.DeviceID);
else // check if need to update a modal on the dashboard
{
foreach (var key in SignalrClient.DevicesDictionary.Keys)
{
var devices = SignalrClient.DevicesDictionary[key];
if (devices != null)
{
if (devices.Contains(device.DeviceID))
SignalrClient.UpdateModal(key, device.DeviceID);
}
}
}
}
}
class SignalrClient
{
public static async Task Start()
{
if (_hubConnection == null || _hubConnection.State == ConnectionState.Disconnected)
{
_hubConnection = new HubConnection("http://stevessiteofamazingboats.net/");
_dashboardHubProxy = _hubConnection.CreateHubProxy("DashboardHub");
_dashboardHubProxy.On("OnRegisterDevice", new Action<string, int>(OnRegisterDevice));
_dashboardHubProxy.On("OnDeregisterDevices", new Action<string>(OnDeregisterDevices));
_dashboardHubProxy.On("OnDeregisterDevice", new Action<string, int>(OnDeregisterDevice));
await _hubConnection.Start();
}
}
public static async void UpdateModal(string connectionId, int deviceId)
{
await Start();
if (_hubConnection.State == ConnectionState.Connected)
await _dashboardHubProxy.Invoke("UpdateModal", new object[] { connectionId, deviceId });
}
}
public class DashboardHub : Hub
{
private static string EventHubConnectionId {get;set;}
private AlarmDBEntities db = Utils.DbContext;
public void UpdateModal(string connectionId, int deviceId)
{
var db = Utils.DbContext;
var device = db.Device.Find(deviceId);
var modal = new Portal.DeviceModalViewModel()
{
DeviceId = deviceId,
SuctionGroups = device.Device1.Where(x => (Enumerables.DeviceType)x.Type == Enumerables.DeviceType.SuctionGroup).Select(x => new DeviceModalViewModel.SGNode()
{
SubChildren = x.Device1.Where(y => (Enumerables.DeviceType)y.Type == Enumerables.DeviceType.Compressor).Select(y => new DeviceModalViewModel.DeviceNode()
{
DeviceId = y.DeviceID,
Name = y.Name,
Amp = db.Property.Where(z => z.Name == "Amps" && z.DeviceID == y.DeviceID).OrderByDescending(z => z.CreatedOn).Select(z => z.Value).FirstOrDefault()
}).OrderBy(y => y.Name).ToList()
}).OrderBy(x => x.Name).ToList(),
};
}
Client-side javascript. The viewModel contains a malformed name:
Viewable on JSFiddle
https://jsfiddle.net/wmqdyv8r/
This is our Angular console error:
angular.min.js:6 Uncaught Error: [ng:areq]
http://errors.angularjs.org/1.5.7/ng/areq?
p0=HeaderController&p1=not%20a%20function%2C%20got%20undefined
at angular.min.js:6
at sb (angular.min.js:22)
at Qa (angular.min.js:23)
at angular.min.js:89
at ag (angular.min.js:72)
at m (angular.min.js:64)
at g (angular.min.js:58)
at g (angular.min.js:58)
at g (angular.min.js:58)
at g (angular.min.js:58)
angular.min.js:312 WARNING: Tried to load angular more than once.
This Highcharts error shows up if we try to open a chart after the SignalR refresh:
store.js:856 Uncaught TypeError: $(...).highcharts is not a function
at Object.success (store.js:856)
at c (<anonymous>:1:132617)
at Object.fireWith [as resolveWith] (<anonymous>:1:133382)
at b (<anonymous>:1:168933)
at XMLHttpRequest.<anonymous> (<anonymous>:1:173769)
Also, after closing the modal, our main page will refresh and now throws this error:
Exception: Sequence contains no elements
Type: System.InvalidOperationException
The main concern is that the update event is breaking something. The naming issue is a lower priority although I'm sure it's related.
Found and fixed the problem!
The malformed name was found to always be trimming the first 5 characters off of the real name, so I fixed that down near the bottom, although I still don't know where this trimming occurs.
The more serious issue, the breaking of scripts was solved as well.
In the UpdateModal method, one of the scripts was looking for a storeID field, along with the deviceID field. After printing a log to the Chrome javascript console, I could see that storeID was always returning 0, even though it was previously initialized before the UpdateModal method.
All I had to do, was follow the damn train add the storeID field seen here under DeviceId:
public void UpdateModal(string connectionId, int deviceId)
{
var db = Utils.DbContext;
var device = db.Device.Find(deviceId);
var modal = new Portal.DeviceModalViewModel()
{
DeviceId = deviceId,
*THIS*-> StoreId = db.Device.Where(x => device.Name.Contains(x.Name.Replace("-Store", "")) && x.ParentID == null).Select(x => x.DeviceID).FirstOrDefault(),
SuctionGroups = device.Device1.Where(x => (Enumerables.DeviceType)x.Type ==
Enumerables.DeviceType.SuctionGroup).Select(x => new
DeviceModalViewModel.SGNode()
{
SubChildren = x.Device1.Where(y => (Enumerables.DeviceType)y.Type ==
Enumerables.DeviceType.Compressor).Select(y => new
DeviceModalViewModel.DeviceNode()
{
DeviceId = y.DeviceID,
*ALSO THIS*-> Name = "12345Comp " + y.Name.Substring(y.Name.Length - 2),
Amp = db.Property.Where(z => z.Name == "Amps" && z.DeviceID == y.DeviceID).OrderByDescending(z => z.CreatedOn).Select(z => z.Value).FirstOrDefault()
}).OrderBy(y => y.Name).ToList()
}).OrderBy(x => x.Name).ToList(),
};
i am creating a form which can be accessed based on condition in MVC. I have first view with dropdownlist and submit button, i want when the submit button is clicked, the value in dropdownlist is passed and compared with condition set for that value, and if the condition is not ok, it shows alert rather than processing to the form.
Here is my code:
public ActionResult ChooseType()
{
var x = DataAccess.GetEmployee(#User.Identity.Name);
var lists = new SelectList(RuleAccess.GetAllRule(), "ID", "TypeDetail");
ViewBag.CategoryId = lists;
/*rule*/
ViewBag.comp1 = Logic.AnnualToogle(#User.Identity.Name);
if (x.EmpSex == "F" && x.EmpMaritalSt == "NIKAH")
{ ViewBag.comp2 = 1; }
else ViewBag.comp2 = 0;
return View();
}
[HttpGet]
public ActionResult Create(int lv_type)
{
var type = RuleAccess.GetTypeByID(lv_type);
ViewBag.type = type;
var model = new LeaveApplicationViewModels();
model.X = DataAccess.GetEmployee(#User.Identity.Name);
model.C = DataAccess.GetLeaveApp(#User.Identity.Name);
/*disable*/
ViewBag.dis = DataAccess.GetDisabledDate(#User.Identity.Name);
/*max*/
var max= RuleAccess.GetMaxByID(lv_type);
ViewBag.c = max;
if (lv_type == 1)
{
var used = RuleAccess.CountUsedAnnual(#User.Identity.Name);
var rem = max - used;
ViewBag.a = used;
ViewBag.b = rem;
}
else
{
ViewBag.b = max;
}
return View(model);
}
I used the Viewbag.comp 1 & 2 in my view:
<script type="text/javascript">
var x = #ViewBag.comp1;
var y = #ViewBag.comp2;
function validatecreate()
{
var value= document.getElementById("lv_type").value;
if (value==1)
{
if(x==1)
document.getElementById('validatecreate').submit();
else { alert('Action cant be done. You either have another annual leave application in pending status or you have reach the limit of annual leave'); }
}
else if(value==2)
{
if(y==1)
document.getElementById('validatecreate').submit();
else { alert('Action cant be done. You either are Male or Not Married Yet'); }
}
else if(value==3)
{
document.getElementById('validatecreate').submit();
}
else {
document.getElementById('validatecreate').submit();
//alert('Http Not Found');
}
}
#Html.DropDownList(
"lv_type", (SelectList) ViewBag.CategoryId,
"--Select One--",
new{ //anonymous type
#class = "form-control input-sm"
}
)
I feel like im doing it wrong especially because if someone manually put the url with ?lv_type=2, they not validate and can go to the form directly. But i need the value of lv_type bcs i use that in my view. Please Helpp :(
Validation must always be done on the server, and client side validation should only be considered a nice bonus that minimizes the need for to a call to the server. And presenting options in a dropdownlist to a user and then telling them thay can't select that option is an awful user experience. Instead, you should be presenting only those options which are applicable to the user (and delete all the scripts you have shown).
Create an additional method in your RuleAccess class, say GetEmployeeRules(Employee employee) which returns only the rules that are applicable to that employee, for example
public static List<Rule> GetEmployeeRules(Employee employee)
{
// Get the list of all rules
if (employee.EmpSex == "F" && employee.EmpMaritalSt == "NIKAH")
{
// Remove the appropriate Rule from the list
}
.....
// Return the filtered list
}
In addition, you should be using a view model in the view
public class LeaveTypeVM
{
[Required(ErrorMessage = "Please select a leave type")]
public int SelectedLeaveType { get; set; }
public IEnumerable<SelectListItem> LeaveTypeList { get; set; }
}
Then in the ChooseType() method
public ActionResult ChooseType()
{
var employee = DataAccess.GetEmployee(#User.Identity.Name);
var rules = RuleAccess.GetEmployeeRules(employee);
var model = new LeaveTypeVM()
{
LeaveTypeList = new SelectList(rules, "ID", "TypeDetail")
};
return View(model);
}
and in the view
#model LeaveTypeVM
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.SelectedLeaveType, Model.LeaveTypeList, "--Select One--", new { #class = "form-control input-sm" }
#Html.ValidationMessageFor(m => m.SelectedLeaveType)
<input type="submit" value="Submit" />
}
and submit to a POST method which allows you to easily return the view if its invalid, or to redirect to the Create method.
[HttpPost]
public ActionResult ChooseType(LeaveTypeVM model)
{
if (!ModelState.IsValid)
{
model.LeaveTypeList = .... // as per GET method
}
return RedirectToAction("Create", new { leaveType = model.SelectedLeaveType });
and in the Create() method
public ActionResult Create(int leaveType)
{
var employee = DataAccess.GetEmployee(#User.Identity.Name);
var rule = RuleAccess.GetEmployeeRules(employee).Where(x => x.ID == leaveType).FirstOrDefault();
if (rule == null)
{
// Throw exception or redirect to an error page
}
var model = new LeaveApplicationViewModels();
....
return View(model);
}
Note your LeaveApplicationViewModels should contain additional properties so that you can avoid all those ViewBag properties and generate a strongly typed view.
Here i use just print the JPanel but i need to put graphics component for drawLine method. how to use it anyone please advice me. my sample code for print JPanel here.
public class Sample {
JPanel component_name = new JPanel();
public void printComponenet(){
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(" Print Component ");
pj.setPrintable (new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum){
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
component_name.printAll(g2);
return Printable.PAGE_EXISTS;
}
});
if (pj.printDialog() == false)
return;
try {
pj.print();
} catch (PrinterException ex) {
// handle exception
}
}
Add
g2.drawLine(left,top,width,height);
Replacing ( or assigning to ) the four parameters with integer values you want to use. eg:
g2.drawLine(30,40,400,300);
Should work for most displays.
g2.setColor(r,g,b);
Before, if you want other than black.
I have created a variable length list according to the many great posts by Steve Sanderson on how to do this in MVC 2. His blog has a lot of great tutorials.
I then created a custom "requiredif" conditional validator following this overview http://blogs.msdn.com/b/simonince/archive/2010/06/11/adding-client-side-script-to-an-mvc-conditional-validator.aspx
I used the JQuery validation handler from the MSDN blog entry which adds the following to a conditional-validators.js I include on my page's scripts:
(function ($) {
$.validator.addMethod('requiredif', function (value, element, parameters) {
var id = '#' + parameters['dependentProperty'];
// Get the target value (as a string, as that's what actual value will be)
var targetvalue = parameters['targetValue'];
targetvalue = (targetvalue == null ? '' : targetvalue).toString().toLowerCase();
// Get the actual value of the target control
var actualvalue = ($(id).val() == null ? '' : $(id).val()).toLowerCase();
// If the condition is true, reuse the existing required field validator functionality
if (targetvalue === actualvalue)
return $.validator.methods.required.call(this, value, element, parameters);
return true;
});
})(jQuery);
Alas, this does not cause a client-side validation to fire ... only the server-side validation fires. The inherent "required" validators DO fire client-side, meaning I have my script includes set-up correctly for basic validation. Has anyone accomplished custom validators in a variable length list in MVC 2 using JQuery as the client-side validation method?
NOTE that this same custom validator works client-side using the exact same set-up on a non-variable length list.
Turns out that it was a field ID naming issue with the way that collection IDs render in a variable length list. The validator was attempting to name the element ID of the dependent property with the expected statement of:
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(Attribute.DependentProperty);
I analyzed the HTML viewsource (posted in my comment, above), and actually, [ and ] characters are not output in the HTML of the collection-index elements... they're replaced with _... so, when I changed my CustomValidator.cs to have the dependent property set to:
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(Attribute.DependentProperty).Replace("[", "_").Replace("]", "_");
... then the client-side validator works since the name matches. I'll have to dig deeper to see WHY the ID is getting renamed in Sanderson's collection index method, below...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Sendz.WebUI.Helpers
{
public static class HtmlPrefixScopeExtensions
{
private const string IdsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
{
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
var itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine(
string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />",
collectionName, html.Encode(itemIndex)));
return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
}
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
{
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}
private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
{
// We need to use the same sequence of IDs following a server-side validation failure,
// otherwise the framework won't render the validation error messages next to each item.
var key = IdsToReuseKey + collectionName;
var queue = (Queue<string>)httpContext.Items[key];
if (queue == null)
{
httpContext.Items[key] = queue = new Queue<string>();
var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
if (!string.IsNullOrEmpty(previouslyUsedIds))
foreach (var previouslyUsedId in previouslyUsedIds.Split(','))
queue.Enqueue(previouslyUsedId);
}
return queue;
}
#region Nested type: HtmlFieldPrefixScope
private class HtmlFieldPrefixScope : IDisposable
{
private readonly string _previousHtmlFieldPrefix;
private readonly TemplateInfo _templateInfo;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
{
_templateInfo = templateInfo;
_previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
#region IDisposable Members
public void Dispose()
{
_templateInfo.HtmlFieldPrefix = _previousHtmlFieldPrefix;
}
#endregion
}
#endregion
}
}
A complete validator / attribute reference...
public class RequiredIfAttribute : ValidationAttribute
{
private RequiredAttribute innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}
public override bool IsValid(object value)
{
return innerAttribute.IsValid(value);
}
}
public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, RequiredIfAttribute attribute)
: base(metadata, context, attribute) { }
public override IEnumerable<ModelValidationResult> Validate(object container)
{
// Get a reference to the property this validation depends upon
var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty);
if (field != null)
{
// Get the value of the dependent property
var value = field.GetValue(container, null);
// Compare the value against the target value
if ((value == null && Attribute.TargetValue == null) ||
(value != null && value.ToString().ToLowerInvariant().Equals(Attribute.TargetValue.ToString().ToLowerInvariant())))
{
// A match => means we should try validating this field
if (!Attribute.IsValid(Metadata.Model))
// Validation failed - return an error
yield return new ModelValidationResult { Message = ErrorMessage };
}
}
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule()
{
ErrorMessage = ErrorMessage,
ValidationType = "requiredif"
};
var viewContext = (ControllerContext as ViewContext);
var depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(Attribute.DependentProperty).Replace("[", "_").Replace("]", "_");
rule.ValidationParameters.Add("dependentProperty", depProp);
rule.ValidationParameters.Add("targetValue", Attribute.TargetValue.ToString());
yield return rule;
}