Web Browser Control in window application - winforms

Hello i am using this code:
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("about:blank");
HtmlDocument doc = webBrowser1.Document;
doc.Write("<b><i>My Name</i> is Not </b> Khan.<b><i>My Name</i> is Not </b> Khan.<b><i>My Name</i> is Not </b> Khan.<b><i>My Name</i> is Not </b> Khan.");
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("about:blank");
HtmlDocument doc = webBrowser1.Document;
doc.Write("<b><i>My Name</i> is Not </b> Khan.<b>");
}
but when i clicked on button then webBrowser1 show blank.

Try Below code:
private void Form1_Load(object sender, EventArgs e)
{
string strText = "<b><i>My Name</i> is Not </b> Khan.<b><i>My Name</i> is Not </b> Khan.<b><i>My Name</i> is Not </b> Khan.<b><i>My Name</i> is Not </b> Khan.";
webBrowser1.Navigate("about:blank");
HtmlDocument objHtmlDoc = this.webBrowser1.Document;
objHtmlDoc.Write(String.Empty);
webBrowser1.DocumentText = strText;
}
private void button1_Click(object sender, EventArgs e)
{
string strText="<b><i>My Name</i> is Not </b> Khan.<b>";
webBrowser1.Navigate("about:blank");
HtmlDocument objHtmlDoc = this.webBrowser1.Document;
objHtmlDoc.Write(String.Empty);
webBrowser1.DocumentText = strText;
}

Related

The name 'modelItem' does not exist in the current context (inside foreach loop)

I have a .NET Core 2.0 Application here and, in one of my views, I used a foreach loop to display all of the items in this database table. Everything was working great. Now I've added another foreach loop inside that one contained in a Bootstrap modal to show a list of IDs but now I'm getting an error that says
The name 'modelItem' does not exist in the current context
I'm sure of the reason. It looks like everything is right. Can someone point out why I'm getting this error or provide an alternative way to pull the desired information from the DB to display in this modal?
View
#foreach (var Submission in Model.Submissions)
{
<div class="col-sm-3">
// Code that populates the project cards on the page
</div>
<!-- Modal -->
<div class="modal fade" id="StatusCodeUpdate-#Submission.ID" tabindex="-1" role="dialog" aria-labelledby="StatusCodeUpdateLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="StatusCodeUpdateLabel">Update Status Code for #Submission.Title </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Status Codes</h6>
<form method="post">
#foreach (var Code in Model.StatusCodes)
{
#Html.DisplayFor(modelItem = Code.ID) // ERROR!!!
}
</form>
</div>
...
}
Code Behind
public class TeamleadModel : PageModel
{
public IList<Submission> Submissions { get; set; }
public IList<Status> StatusCodes { get; set; }
private readonly SubmissionContext _submissionContext;
private readonly StatusContext _statusContext;
public TeamleadModel(SubmissionContext submission, StatusContext statusContext)
{
_submissionContext = submission;
_statusContext = statusContext;
}
public async Task OnGetAsync()
{
Submissions = await _submissionContext.Submissions.ToListAsync();
StatusCodes = await _statusContext.StatusCodes.ToListAsync();
}
Try #Html.DisplayFor(modelItem => Code.ID). You've got an assignment instead of lambda expression.

select option with Angular and .net core

I have angular controller for get and post some data.
I made two controller to work correctly and now when I made 3rd one with mixing two previous controllers get and post doesn't work. Could you help to find a problem ?
Here is a code.
sparePartController.js
//sparePartController.js
(function () {
"use strict";
angular.module("app")
.controller("sparePartController", sparePartController);
function sparePartController($http)
{
var vm = this;
vm.spareParts = [];
vm.newSparePart = {};
vm.errorMessage = "";
vm.isBusy = true;
$http.get("/spares/getAll")
.then(function (response) {
//success
angular.copy(response.data, vm.spareParts);
}, function (error) {
vm.errorMessage = error;
}).finally(function () {
vm.isBusy = false;
});
vm.addSparePart = function () {
vm.isBusy = true;
vm.errorMessage = "";
$http.post("/spares", vm.newSparePart)
.then(function (response) {
console.log("test");
vm.spareParts.push(response.data);
vm.newSparePart = {};
}, function () {
console.log = "failed to save new spare";
vm.errorMessage = "failed to save new spare";
}).finally(function () {
vm.isBusy = false;
});
};
}
})();
Index.cshtml to show spare parts and add new one
#model IEnumerable<RnD.Models.ViewModels.SparePartViewModel>
#{
ViewBag.Title = "Spare Parts List";
}
#section scripts{
<script src="~/lib/angular/angular.js"></script>
<script src="~/js/app.js"></script>
<script src="~/js/sparePartController.js"></script>
<script src="~/js/spareTypeController.js"></script>
<script src="~/js/machineController.js"></script>
}
<div class="row" ng-app="app" ng-controller="sparePartController as vm">
<!-- Start Modal-->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Create New Spare Part
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<form novalidate name="newSpareForm" ng-submit="vm.addSparePart()">
<div class="form-group">
<label for="InternalCode">Internal Code</label>
<input class="form-control" type="text" placeholder="Internal Code" id="InternalCode" ng-model="vm.newSparePart.internalCode" required min="3" />
</div>
<div class="form-group" ng-controller="machineController as machineVM">
<label>Machine Type</label>
<select class="form-control" ng-model="machineVM.machineType" ng-options="machine.name for machine in machineVM.machines"></select>
</div>
<div class="form-group" ng-controller="spareTypeController as spareVM">
<label>Spare Type</label>
<select class="form-control" ng-model="spareVM.id">
<option ng-repeat="spare in spareVM.spares" value="{{spare.id}}">{{spare.name}}</option>
</select>
</div>
<div class="form-group">
<input type="submit" value="Add" class="btn btn-success" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<!-- End Modal-->
</div>
<hr />
<div class="panel panel-default" ng-repeat="spare in vm.spareParts">
<div class="panel-heading">
{{spare.internalCode}} //it was vm.internalCode
</div>
<div class="panel-body">
</div>
<div class="panel-footer">
</div>
</div>
</div>
P.S. To add, when I want to post I have problem to catch value from select. Internal code is recognized from angular controller but machinetype it is not recognized that filed always is null.
here is modelview class
public class SparePartViewModel
{
[Required]
[StringLength(100)]
public string InternalCode { get; set; }
[StringLength(4096)]
public string Description { get; set; }
[StringLength(255)]
public string NameOnFolder { get; set; }
public decimal? Enter { get; set; }
public decimal? Exit { get; set; }
public decimal? Thickness { get; set; }
public string Band { get; set; }
public string Color { get; set; }
public bool Elastic { get; set; }
[Required]
public MachineType MachineType { get; set; }
[Required]
public virtual SpareType SpareType { get; set; }
}
I even try in index.cshtml to put this code <select class="form-control" ng-model="vm.newSparePart.machineType" ng-options="machine.name for machine in machineVM.machines"></select> but in this case when I call [From Body] my viewModel is null
Here is my SparePartsController.cs
[Route("/spares")]
[Authorize]
public class SparePartsController : Controller
{
private ILogger<SparePartsController> _logger;
private ISparePartRepository _repository;
public SparePartsController(ISparePartRepository repository, ILogger<SparePartsController> logger)
{
_logger = logger;
_repository = repository;
}
[HttpGet("")]
public IActionResult Index()
{
return View();
}
[HttpGet("getAll")]
public IActionResult Get()
{
try
{
var results = _repository.GetAllSpares();
return Ok(Mapper.Map<IEnumerable<SparePartViewModel>>(results));
}
catch (Exception ex)
{
_logger.LogError($"Failed to get all Spares : {ex}");
return BadRequest("Error Occurred");
}
}
[HttpPost("")]
public async Task<IActionResult> Post([FromBody]SparePartViewModel viewModel)
{
if (ModelState.IsValid)
{
var newSpare = Mapper.Map<SparePart>(viewModel);
_repository.AddSpare(newSpare);
if (await _repository.SaveChangesAsync())
{
return Created($"spare/{newSpare.InternalCode}", Mapper.Map<SparePartViewModel>(newSpare));
}
}
return BadRequest("Failed to save spare.");
}
}
I see a few things off here. 1. I don't think /spares is the full URL to the add method. 2. Even if it were, you still need to send it a correct signature - i.e. the items within the object you send need to match with items in the add spares method signature. 3. I don't see where your newSparePart object is getting assigned values; it's just an empty object. Share the method signature for your add spare method so we can verify that the serialized object. Which brings up 4. You likely need to serialize your object to json: JSON.stringify(vm.newSparePart) when you send it via HTTP post.

the server responded with a status of 500 (Internal Server Error)(asp.net mvc and angular js)

I am Getting null value in action method when i am pass data from angular js to action method. i debug and see it hit to the AddCutomer method but data is null(the server responded with a status of 500 (Internal Server Error). can anyone help me to fix this issue
Admin.js
var app = angular.module("adminmdl", [])
app.controller("admincontroller", function ($scope, AdminService) {
$scope.Action = 'Add';
GetAllCustomer();
function GetAllCustomer() {
var getcust = AdminService.getCustomer();
getcust.then(function (cust) {
$scope.customers = cust.data;
}, function () {
alert('Error');
});
}
$scope.data = {
cus_code: '',
cus_name: ''
}
$scope.savecu = function () {
AdminService.saveCustomerDdetails($scope.cusmodel).then(function (d) {
$scope.msg = "Insert Successfully";
});
}
})
.service('AdminService', function ($http) {
this.getCustomer = function () {
return $http.get('GetCustomer');
}
this.saveCustomerDdetails = function (customer) {
return $http.post('/AddCutomer', customer);
}
})
ASP.NET MVC
[HttpPost]
public JsonResult AddCutomer(Customer customer) {
te.Customers.Add(customer);
te.SaveChanges();
string message = "Success";
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
html code
<form class="form-horizontal" method="post" ng-submit="savecu()" name="basic_validate" id="basic_validate" novalidate="novalidate">
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customercode" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customername" name="name" id="name" >
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Save" ng-click="savecu()" class="btn btn-success">
<input type="submit" value="Clear" class="btn btn-success" />
</div>
</div>
<div class="control-group">
<div class="controls">
<p style="color:green">{{msg}}</p>
</div>
</div>
#*<div class="form-actions">
</div>*#
</form>
Ok, so this is your autogenerated class
public partial class Customer
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.??Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Customer()
{
this.projects = new HashSet<project>();
}
public string cus_code { get; set; }
public string cus_name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.??Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<project> projects { get; set; }
}
The first issue I see is that your client object that you post to the server doesn't match the class definition.
Change the ng-models to cusmodel.cus_code and cusmodel.cus_name
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.cus_code" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.cus_name" name="name" id="name" >
</div>
</div>
The names in the scope model need to match the class specification else the json deserializer don't know what to do here.
Try to make a new post when these changes are added and see if the values of the cus_code and cus_name is populated.
If this doesn't work I would use a data transfer object to handle the communication with the client instead. Populating autogenerated classes from EF(or what orm you use) from the client can be a mess.
Add this class:
public class CustomerDTO
{
public string cus_code { get; set; }
public string cus_name { get; set; }
}
And use it in the controller method
[HttpPost]
public JsonResult AddCutomer(CustomerDTO customer) {
var cust = new Customer{ cus_code = customer.cus_code, cus_name = customer.cus_name };
te.Customers.Add(cust);
te.SaveChanges();
string message = "Success";
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Angular JS form validation using ModelState in Web API Core

I am working on a Web Application with client side in AngularJS, TypeScript and HTML, and the server side is a .NET Core Web API.
I want to implement server side validation using ModelState and DTOs. The thing is that I don't want to display all the validation errors at the top of the Form, but I want to display them in-line with the textbox
So first I added the validations to a DTO and then checking in the controller for ModelState.IsValid
public class TestDTO
{
[Required(ErrorMessage = "This field is required")]
public string TestName { get; set; }
}
public class ManyTestDTO
{
[Required(ErrorMessage = "Many Item is required")]
public string ManyItem { get; set; }
}
public class RestaurantDTO
{
public int RestaurantId { get; set; }
[Required(ErrorMessage = "This field is required")]
public string Name { get; set; }
[Required(ErrorMessage = "This field is required"), MaxLength(20), MinLength(1)]
public string Description { get; set; }
[Required(ErrorMessage = "This field is required")]
public string Address { get; set; }
public TestDTO TestModel { get; set; }
public List<ManyTestDTO> TestMany { get; set; }
public RestaurantDTO()
{
}
}
Getting the idea from this link: Link - I have created a directive in my Application to display the validation message in-line, it is working fine the problem is that the HTML I am writing to show the validation message is complex.
The Directive
export class ServerValidationDirective implements ng.IDirective {
constructor() { }
restrict: "A";
require: "ngModel";
link = function (scope, element, attrs, ctrl) {
scope.$watch("controller.modelState", () => {
let modelState = scope.controller.modelState;
console.log(modelState);
if (modelState == null) return;
let state = modelState[attrs.ngServerValidate];
if (state) {
// Server Errors exist for the ngServerValidate
scope.controller.parsedModelState[attrs.ngServerValidate] = state;
} else {
// No Error for the ngServerValidate
if (scope.controller.parsedModelState[attrs.ngServerValidate]) {
scope.controller.parsedModelState[attrs.ngServerValidate] = null;
}
}
});
};
static factory(): ng.IDirectiveFactory {
var directive = () => new ServerValidationDirective();
return directive;
}
}
The Controller:
class CreateRestaurantController {
static $inject = ["$scope"];
restaurantModel: any;
modelState: any;
parsedModelState: any;
testModelState:any;
constructor($scope) {
this.scope = $scope; // create a local copy of the $scope
this.scope.controller = this; //put controller reference in this.scope.controller
this.restaurantModel = {name: "Dawood",testModel: {},testMany: [{ ManyItem: "I have a Value" },{}]};
this.modelState = null;
this.parsedModelState = {};
this.testModelState = JSON
.parse('{"Address":["This field is required"],"Description":["This field is required"],"TestModel.TestName":["This field is required"],"TestMany[1].ManyItem":["Many Item is required"]}');
console.log(this.testModelState);
}
testValidation() {
this.modelState = this.testModelState;
//Normally modelStae will be return from server
// Submit to Server
//this.apiService.post("/api/RestaurantDashboard/GetTestValidation",
// null, this.restaurantModel,
// response => {
// console.log(response);
// },
// response => {
// this.modelState = response.data;
// });
}
}
The HTML for the Form
<div ng-app="validationApp">
<div ng-controller="validationController">
<form name="restaurantForm" class="form">
<div class="form-group" ng-class="{'has-error': controller.parsedModelState.Name != null}">
<label>Restaurant Name</label>
<input type="text" class="form-control" ng-server-validate="Name" ng-model="controller.restaurantModel.name">
<span class="help-block" ng-repeat="errorMessage in controller.parsedModelState.Name"> {{errorMessage}} </span>
</div>
<div class="form-group" ng-class="{'has-error': controller.parsedModelState.Address != null}">
<label>Address</label>
<input type="text" class="form-control" ng-server-validate="Address" ng-model="controller.restaurantModel.address">
<span class="help-block" ng-repeat="errorMessage in controller.parsedModelState.Address"> {{errorMessage}} </span>
</div>
<h3>Nested Object</h3>
<div class="form-group" ng-class="{'has-error': controller.parsedModelState['TestModel.TestName'] != null}">
<label>TestModel.TestName</label>
<input type="text" class="form-control" ng-server-validate="TestModel.TestName" ng-model="controller.restaurantModel.testModel.testName">
<span class="help-block" ng-repeat="errorMessage in controller.parsedModelState['TestModel.TestName']"> {{errorMessage}} </span>
</div>
<h3>Many Array/List</h3>
<ul class="list-unstyled">
<li ng-repeat="item in controller.restaurantModel.testMany">
<div class="form-group" ng-class="{'has-error': controller.parsedModelState['TestMany[' + $index + '].ManyItem'] != null}">
<label>Many Item {{$index}}</label>
<input type="text" class="form-control" ng-server-validate="{{'TestMany[' + $index + '].ManyItem'}}" ng-model="item.ManyItem">
<span class="help-block" ng-repeat="errorMessage in controller.parsedModelState['TestMany[' + $index + '].ManyItem']"> {{errorMessage}} </span>
</div>
</li>
</ul>
<button class="btn btn-primary" ng-click="controller.testValidation()">Click Me to Check</button>
</form>
</div>
</div>
As you can see the HTML structure for the Many Array/List and Nested Object is a bit complex. Is there a better way to do this?
Fiddle: https://jsfiddle.net/mdawood1991/ua9mk7qz/

AngularJS POST to Server

I have an angularJS form which posts data to a Java Servlet, but I am not seeing the request go through; servlet "create" wasn't called.
Here's my code:
test.html
<body>
<form ng-controller="UserController">
<legend>Create User</legend>
<label>Name</label>
<input type="text" id="name" name="name" ng-model="name" placeholder="User Name">
<label>Email</label>
<input type="text" id="email" name="email" ng-model="email" placeholder="ur email here">
<label>Password</label>
<input type="text" id="pwd" name="pwd" ng-model="pwd" placeholder="ur own pwd here">
<button ng-submit="createUser()" class="btn btn-primary">Register</button>
</form>
</body>
script.js
function UserController($scope, $http) {
$scope.user = {};
$scope.createUser = function() {
$http({
method : 'POST',
url : '/create',
data : 'name=' + $scope.user.name + '&email=' + $scope.user.email,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
})
}
my servlet is as below,but it doesn't print "Post" an all.
public class FirstServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
System.out.println("Get");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
System.out.println("Post");
}
}
The web server is jetty,and the web.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>createUser</servlet-name>
<servlet-class>servlet.FirstServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>createUser</servlet-name>
<url-pattern>/create</url-pattern>
</servlet-mapping>
</web-app>
To post data to a web server, you will want to bind your form values to a object in the $scope, and then submit that object to the script.
The trick is to submit the entire object "user" to the server, and Angular will automatically format it in JSON. Also, "user" was not being used by the ng-model tags.
Another thing to note is that you will probably want to include something for the app to do when it finishes the request. You can use the methods ".success(function(data){})" and ".error(...)" to do this (these are methods on the promise $http returns).
I've included both PHP and Servlet code; it is the same, however, for all server scripts (JSON data from Angular).
HTML
<body>
<form ng-controller="UserController" ng-submit="createUser()">
<legend>Create User</legend>
<label>Name</label>
<input type="text" id="name" name="name" ng-model="user.name" placeholder="User Name">
<label>Email</label>
<input type="text" id="email" name="email" ng-model="user.email" placeholder="ur email here">
<label>Password</label>
<input type="text" id="pwd" name="pwd" ng-model="user.pwd" placeholder="ur own pwd here">
<button class="btn btn-primary">Register</button>
</form>
</body>
</html>
Controller
function UserController($scope, $http) {
$scope.user = {};
$scope.createUser = function() {
$http({
method : 'POST',
url : '/create',
data : $scope.user
})
}
Example Server Code: PHP
$data = file_get_contents("php://input");
$objData = json_decode($data);
$pwd = $objData -> pwd;
$user = $objData -> name; //etc
Example Server Code: JAVA Servlet
JSONObject jObj = new JSONObject(request.getParameter("mydata")); // this parses the json
Iterator it = jObj.keys(); //gets all the keys
while(it.hasNext())
{
String key = it.next(); // get key
Object o = jObj.get(key); // get value
//do something with it here
//you can also do:
String user = jObj.get("user");
}
Changing ng-submit to ng-click should do the trick.

Resources