|
I am trying to run the task in a child thread, but I'm not able to get notification when a child thread complete its task.
|
|
|
|
|
|
The simplest way to do this is via a BackgroundWorker: BackgroundWorker Class (System.ComponentModel)[^] - it provides events to indicate progress and completion which makes it very simple to use.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
I am new to the .NET environment and trying to write a simple MVC application to read student data and display it to the end user. I have connected to a database using SQLOLEDB, the code of which I have pasted below. The data obtained from the query was stored in a variable of the type DataTable. Now I want to see the content of the query result in the form of a JSON output for which I have a faintest idea that I have to create a new controller. But I am not able to proceed beyond this point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
namespace Database.model
{
public class student
{
public int id { get; set; }
public string name { get; set; }
private string age { get; set; }
public DataTable GETSQLServerData()
{
var _connectionobject = new SqlConnection();
_connectionobject.ConnectionString = @"Provider=SQLOLEDB;Data Source=PHYSICS\SQLEXPRESS;Persist Security Info=true;Initial Catalog=master;Integrated Security=True; provider = SQLOLEDB;";
_connectionobject.Open();
var _commandObject = new SqlCommand();
_commandObject.CommandText = "select * from dbo.tblStudent";
_commandObject.ExecuteReader();
var _dataReader = _commandObject.ExecuteReader();
DataTable obj2 = new DataTable();
obj2.Load(_dataReader);
_connectionobject.Close();
return obj2;
}
}}
With Regards
Nikhilesh Murty
|
|
|
|
|
Why do you want to convert a DataTable to JSON just to convert is back to something viewable? You can connect your DataTable direct to your View. There are many MVC articles that will explain how to do it.
|
|
|
|
|
Google "convert datatable to json" for ideas. Further to what Richard posted I am going to assume you are getting the data via ajax, as if not there is no point in converting your table to JSON, just render it directly to the view.
|
|
|
|
|
Hello best codeproject members,
I have a problem that i can not resolve. I hope someone can get me on the right 'code' I have implant to my code a 'javascript' (there was already a input file for a url, but i decided to add also a file upload button), wenn i go to the site and 'create a new message' and try to upload the file it gives me a 'image not suported error'. Here is a part of the script;
Thank you
The Div;
<div class="form-group">
<input type="file" class="btn btn-default btn-file" style="width:70%" id="file" name="file" />
<input type="button" value="Upload" class="btn btn-primary uploadbtn" id="uploadimg" name="upladimage" />
<img class="wait hide" id="wait" src="/Content/img/pleasewait .gif" />
You can upload the only image file.
</div>
The Javascript;
$("#imgurl").keyup(
function () {
$("#pmainimg").attr("src", $("#imgurl").val());
});
$(document).on('click', '#uploadimg', function () {
if (window.FormData !== undefined) {
var fileUpload = $("#file").get(0);
var files = fileUpload.files;
var fileData = new FormData();
if ($("#file").val()!='') {
fileData.append(files[0].name, files[0]);
$("#wait").removeClass("hide");
$("#wait").addClass("show");
$.ajax({
url: '/Member/UploadImage',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
if (result.indexOf("http") > -1) {
$("#imgurl").val(result);
$("#pmainimg").attr("src", $("#imgurl").val());
$("#wait").removeClass("show");
$("#wait").addClass("hide");
}
else {
debugger;
$("#errormsg").html("You can upload the only image file.");
$("#errormsg").css("display", "inline");
$("#errormsg").css("color", "red");
$("#wait").removeClass("show");
$("#wait").addClass("hide");
}
},
error: function (err) {
alert("Image Not Supported");
$("#wait").removeClass("show");
$("#wait").addClass("hide");
}
});
}
else
{
$("#errormsg").html("You have not specified a image file.");
$("#errormsg").css("display", "inline");
$("#errormsg").css("color", "red");
$("#wait").removeClass("show");
$("#wait").addClass("hide");
}
} else {
alert("FormData is not supported.");
}
});
Controler;
{
[UserLoginRequired]
public class MemberController : ClickMSGController
{
public ActionResult CreateMessage()
{
return View();
}
public ExpandoObject CreateMessageObject(string ctatitle, string msgtitle, string msgbody, string imgurl,
string linkurl, string linktxt, string reply1, string reply2, string msgname)
{
dynamic button1 = new ExpandoObject();
button1.type = "web_url";
button1.url = linkurl;
button1.title = linktxt;
dynamic button2 = new ExpandoObject();
button2.type = "postback";
button2.title = ctatitle;
button2.payload = Guid.NewGuid().ToString();
dynamic element = new ExpandoObject();
element.title = msgtitle;
element.image_url = imgurl;
element.subtitle = msgbody;
element.buttons = new List<object> { button1, button2 };
dynamic payload = new ExpandoObject();
payload.template_type = "generic";
payload.elements = new List<object> { element };
dynamic attachment = new ExpandoObject();
attachment.type = "template";
attachment.payload = payload;
dynamic message = new ExpandoObject();
message.attachment = attachment;
dynamic fbmsg = new ExpandoObject();
fbmsg.message = message;
if (!string.IsNullOrEmpty(reply1) && !string.IsNullOrEmpty(reply2))
{
dynamic reply1obj = new ExpandoObject();
reply1obj.content_type = "text";
reply1obj.title = reply1;
reply1obj.payload = reply1;
dynamic reply2obj = new ExpandoObject();
reply2obj.content_type = "text";
reply2obj.title = reply2;
reply2obj.payload = reply2;
fbmsg.message.quick_replies = new List<object> { reply1obj, reply2obj };
}
return fbmsg;
}
public ActionResult GetJson(string ctatitle, string msgtitle, string msgbody, string imgurl,
string linkurl, string linktxt, string reply1, string reply2, string msgname)
{
ExpandoObject msgObject = CreateMessageObject(ctatitle, msgtitle, msgbody, imgurl, linkurl, linktxt, reply1, reply2, msgname);
if (Request.Form["savebtn"] == "Save & Get JSON")
{
AdManager.Ad ad = new AdManager.Ad();
ad.AdName = msgname;
ad.CallToAction = ctatitle;
ad.Image_URL = imgurl;
ad.LinkButtonText = linktxt;
ad.LinkButtonURL = linkurl;
ad.Reply1 = reply1;
ad.Reply2 = reply2;
ad.Subtitle = msgbody;
ad.Title = msgtitle;
ad.UserID = CurrentUser.ID;
AdManager.AddAd(ad);
}
ViewBag.Json = Newtonsoft.Json.JsonConvert.SerializeObject(msgObject);
return View("result");
}
public ActionResult Dashboard()
{
return View();
}
public ActionResult ManageMessages()
{
List<AdManager.Ad> ads = AdManager.GetAdsForUser(CurrentUser.ID);
ViewBag.Ads = ads;
return View();
}
public ActionResult EditAd(int ad)
{
AdManager.Ad adv = AdManager.GetAd(ad);
ViewBag.Ad = adv;
return View();
}
[HttpPost]
public ActionResult UpdateAd(string ctatitle, string msgtitle, string msgbody, string imgurl,
string linkurl, string linktxt, string reply1, string reply2, string msgname,int adid)
{
ExpandoObject msgObject = CreateMessageObject(ctatitle, msgtitle, msgbody, imgurl, linkurl, linktxt, reply1, reply2, msgname);
AdManager.Ad ad = new AdManager.Ad();
ad.AdName = msgname;
ad.CallToAction = ctatitle;
ad.Image_URL = imgurl;
ad.LinkButtonText = linktxt;
ad.LinkButtonURL = linkurl;
ad.Reply1 = reply1;
ad.Reply2 = reply2;
ad.Subtitle = msgbody;
ad.Title = msgtitle;
ad.UserID = CurrentUser.ID;
ad.ID = adid;
AdManager.UpdateAd(ad);
ViewBag.Json = Newtonsoft.Json.JsonConvert.SerializeObject(msgObject);
return View("result");
}
public ActionResult UpdateAd(int Ad)
{
ViewBag.Ad= AdManager.GetAd(Ad);
return View();
}
public ActionResult Delete(int Ad)
{
ViewBag.DeletedAd = AdManager.DeleteAd(Ad);
List<AdManager.Ad> ads = AdManager.GetAdsForUser(CurrentUser.ID);
ViewBag.Ads = ads;
return View("ManageMessages");
}
public ActionResult Settings()
{
return View();
}
public ActionResult Help()
{
return View();
}
}
}
|
|
|
|
|
You're trying to post to the UploadImage action on the MemberController .
But according to the code you've posted, that action doesn't exist.
If you debug your Javascript and inspect the err parameter, you'll see a 404 / "not found" error. And if you use the network tools in your browser's developer tools, you'll see the request to Membber/UploadImage returns a 404 / "not found" error message.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello Richard Deeming, Thank you for your respond. I have lookedup and followed your advice. Now it is not givng a 404 error but a 405? (i have linked the to content/img/menmber_image) As far as i know 405 is a block question, could this be a IIS issue? (I'am testing on localhost).
Thank you
|
|
|
|
|
405 is "Method not allowed". This is usually caused by something like your client-side code getting the URL correct but trying to POST whereas the method is expecting a GET, or the other way around.
|
|
|
|
|
hello Dave Kreskowiak, thank you for your response. Little by little i am hopely to the 'working result'. Reading your words, i think i have to add a new cshtml (UploadImage.cshtml) file to my Members folder (I have to set again the firsturl: '/Member/UploadImage',). Should i include the javascript there also?
Thank you
|
|
|
|
|
No, you don't. You just need to figure out why the client-side code is making a call to a method using the mode that the method didn't expect. If the controller method doesn't have a [HttpPost] attribute on it but the client-side code is making a POST call, well, that's a problem. It could be a few things like this.
Adding more files and code isn't going to solve this problem.
|
|
|
|
|
Ultimately I wish to have my app watch for any new processes recording the command line and the owner. I can get the processID, Name, and CommandLine without any issues however since the ManagementEventWatcher returns a ManagementBaseObject and not a ManagementObject (which has a method for .GetOwner) I cannot seem to get the owner.
What I have tried.
- I looked through the properties of the ManagementBaseObject, no method for GetOwner or a property for User.
- I pulled the ProcessID from the ManagementBaseObject (mboEvent["TargetInstance"])["ProcessID"].ToString(). This works as I can get a ManagementObject and then use GetOwner...
The second item does work except that it only works on a slower command (for example Powershell.exe Get-Process) as the process still exists at the time of the query. But quicker commands (like net use or powershell.exe get-services) don't return a username as the process is gone by the time I query for it.
Any help would be amazing, thanks in advance for any help you can give.
|
|
|
|
|
|
Brilliant ! Thank you so much for the quick response. You saved me hours. I very much appreciate it.
|
|
|
|
|
i am using this code
using System;
using System.Windows.Forms;
using System.Timers;
namespace T_TEST
{
public partial class Form1 : Form
{
static System.Timers.Timer timer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
schedule_Timer();
}
static void schedule_Timer()
{
Console.WriteLine("### Timer Started ###");
DateTime nowTime = DateTime.Now;
DateTime scheduledTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 1, 59, 0, 0);
if (nowTime > scheduledTime)
{
scheduledTime = scheduledTime.AddDays(1);
}
double tickTime = (double)(scheduledTime - DateTime.Now).TotalMilliseconds;
timer = new System.Timers.Timer(tickTime);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
timer.Stop();
MessageBox.Show("Hello World!!!");
schedule_Timer();
}
}
}
the above code has one problem that once the timer fire then it will fire next day. i want if timer fire and after few minute if i reset my system time again then it should fire again.
how to customize the above code for my requirement. anyone mind to help me plzzz.
thanks
tbhattacharjee
|
|
|
|
|
You should look at this[^] - it's one of the more obscure events I grant you, but it should be easy enough to hook into this.
This space for rent
|
|
|
|
|
Because you set the tick time to a specific value, means that it fires at that interval, not that it fires at a specific time: it doesn't add the tick interval to the system clock when you start the timer, it sets a specific number of ticks that should elapse before the timer event is fired. Changing the system clock does not affect that tick count, so if you set a timer for one hour and then move the clock forward 59 minutes, it will still be an hour before the timer fires.
If you want to first at a time, then set the timer interval to 30 seconds, and set a class level DateTime value at which you want to call your method. In the tick handler, compare the current time to the class level value and call your method if it matches. That way, you can reset the clock after it fires, and it will match a second time.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
can u plzz post some sample what u said "If you want to first at a time, then set the timer interval to 30 seconds, and set a class level DateTime value at which you want to call your method. In the tick handler, compare the current time to the class level value and call your method if it matches. That way, you can reset the clock after it fires, and it will match a second time."
thanks
tbhattacharjee
|
|
|
|
|
You should be able to do that yourself, if you wrote the code you show! You know how to set the interval on the timer, and you know how to create variables...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
- call your timer (for example) every Minute - set timer.tick to 60000
- when you have the timer.event don't stop the timer
- compare if now is greater or equal your schedule-time, but less your schedule-time +30 seconds - if yes the give the message and increase your schedule-time
modified 24-Feb-17 6:28am.
|
|
|
|
|
Didn't really know where to ask this so went for the lowest common denominated forum! C# FTW!
Anyway, I was wondering if this was a problem that had already been solved but I'm not aware of the generalised approach.
I have an MvvmCross based solution that uses SQLite as the data store. All the common functional goodness is in a core PCL project, all fine and dandy. In this core PCL I have the data access stuff along with resx files containing any strings needed in the various application UI projects.
When the application starts up it initialises a connection to the SQLite database. If the database doesn't yet exist and requires creation (think very first run of the application) it needs to create the database and populate it with some initial data (just for ease of setup with some generic lookup data). This data is fully editable by the user but this is more of a convenience task to get the user up and running quickly without burdening them with loads of config before being able to do something useful.
What I'm looking at is using localised resx data for the source of this look-up data. I can think of a few ways of doing this but before I pop off and roll a solution I was wondering if there were any generalised approaches to this scenario that people had used before.
Googling hasn't turned anything up thus far so I thought I'd cast the net out to you lot first.
|
|
|
|
|
|
I wasn't really looking for general information on app globalisation, I've developed a few globalised apps in my time but I've not been in my current specific situation and wondered if there was a relevant pattern.
Thanks anyway.
|
|
|
|
|
The "recommended patterns" are there. I find it's not worth the effort to go against the grain in these situations. Adopt; then extend, if necessary.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|