c# Form in Class start thread - multithreading

one class sample : testHTTP.class in this code
public String httptest(object httptestx)
{
var data = (Tuple<string, string, string>)httptestx;
var s = data.Item1;
var k = data.Item2;
var p = data.Item3;
............................
}
Form1 thread class not start please help me ... :
private void button5_Click(object sender, EventArgs e)
{
for (Int32 i5 = 0; i5 < textBox5.Lines.Length; i5++)
{
var thr1 = new Thread(dfproJesiHttpClass.httptest());
var data = new Tuple<string, string, string>(textBox6.Lines[i6].Trim(), textBox4.Lines[i4].Trim(), textBox5.Lines[i5].Trim());
thr1.Start(data);
threads.Add(thr1);
}
}

I'd be surprised if that code compiles. You need to change this line:
var thr1 = new Thread(dfproJesiHttpClass.httptest());
to
var thr1 = new Thread(dfproJesiHttpClass.httptest);
Assuming that dfproJesiHttpClass is an instance and not the name of the class.

Related

Missing Return and Float should be Int

I have the codeblock like this and I am trying to get rid of the Float should be Int and Missing Return errors.
package com.bykd.dev;
#:final class Version
{
public static inline var SPLIT_CHAR : String = ".";
public static var revisionKeyword : String = "Revision";
private var _tag : String;
private var _numbers : Array<Dynamic>;
public static function create(pfx : String, rev : String = null, sfx : String = null) : Version
{
var nums : Array<Dynamic> = null;
nums = pfx.split(SPLIT_CHAR);
if (rev != null)
{
nums.push(trimRevision(rev));
}
return new Version(nums, sfx);
private static function trimRevision(rev : String) : String
{
var beg : Float = Math.NaN;
var end : Float = Math.NaN;
beg = Std.string("$" + revisionKeyword + ": ").length;
end = rev.lastIndexOf(" $");
return rev.substring(beg, end);
}
}
Errors are in the last lines :
end = rev.lastIndexOf(" $");
return rev.substring(beg, end);
Any help would be highly appreciated.
Why use Float?
var beg : Int = 0;
var end : Int = 0;
Also avoid Dynamic when possible
var nums : Array<String> = null;
nums = pfx.split(SPLIT_CHAR);

How to convert ASP.Net MVC 5 ExecuteResult to ASP.Net Core ExecuteResultAsync

I'm migrating one of my Asp.Net MVC 5 project to Asp.Net Core. I have a custom ActionResult, which renders the view as partial view if the request was ajax request, and renders the view as normal view with layout if the request was a normal request. I have issues with converting the old ExecuteResult to new ExecuteResultAsync.
Here it is my old code:
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Buffer = true;
context.Controller.ViewData.Model = Model;
using (var sw = new StringWriter())
{
var request = context.RequestContext.HttpContext.Request;
if (string.IsNullOrEmpty(ViewName))
{
ViewName = request.RequestContext.RouteData.GetRequiredString("action");
}
var viewResult = request.IsAjaxRequest()
? ViewEngines.Engines.FindPartialView(context, ViewName)
: ViewEngines.Engines.FindView(context, ViewName, "_Layout");
var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
context.HttpContext.Response.Write(sw.GetStringBuilder().ToString());
}
}
And here it is my half converted code:
public override async Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Response.Buffer = true; //broken
context.HttpContext.Controller.ViewData.Model = Model; //broken
using (var sw = new StringWriter())
{
var request = context.HttpContext.Request;
if (string.IsNullOrEmpty(ViewName))
ViewName = context.ActionDescriptor.Name;
var engine = context.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
var viewResult = request.Headers["X-Requested-With"] == "XMLHttpRequest"
? engine.FindPartialView(context, ViewName)
: engine.FindView(context, ViewName);
var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw, new HtmlHelperOptions()); //broken
await viewResult.View.RenderAsync(viewContext);
await context.HttpContext.Response.WriteAsync(sw.GetStringBuilder().ToString());
}
}
My main issue is the ControllerContext -> ActionContext migrating. Please help me to convert ControllerContext to ActionContext. Thank you very much!
Ehh, put something together to fit RC2 bits real quick. Feel free to improve on it:
public override async Task ExecuteResultAsync(ActionContext context)
{
var request = context.HttpContext.Request;
if (string.IsNullOrEmpty(ViewName))
{
ViewName = context.ActionDescriptor.Name;
}
var engine = context.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
var viewResult = engine.FindView(context, ViewName, isMainPage: request.Headers["X-Requested-With"] != "XMLHttpRequest");
var tempDataProvider = context.HttpContext.RequestServices.GetService(typeof(ITempDataProvider)) as ITempDataProvider;
var modelMetaDataProvider = context.HttpContext.RequestServices.GetService(typeof(IModelMetadataProvider)) as IModelMetadataProvider;
using (var writer = new HttpResponseStreamWriter(context.HttpContext.Response.Body, Encoding.UTF8))
{
var tempData = new TempDataDictionary(context.HttpContext, tempDataProvider);
var viewData = new ViewDataDictionary(modelMetaDataProvider, context.ModelState)
{
Model = Model
};
var viewContext = new ViewContext(
context,
viewResult.View,
viewData,
tempData,
writer,
new HtmlHelperOptions());
await viewResult.View.RenderAsync(viewContext);
}
}

c# two object in class dont work thread

I have a construct like this:
private readonly List<Thread> thr = new List<Thread>();
In a class i have a method with one parameter that i want to call threaded.
public void testthr(object xxx)
{
......
}
on button click i start a thread
for (Int32 i = 0; i < textBox8.Lines.Length; i++)
{
var thr1 = new Thread(testthr);
thr1.Start(textBox8.Lines[i].Trim());
thr.Add(threadz);
}
How to make a thread with more than one parameter? Like:
public void testthr(object xxx, string yyy)
{
......
}
this class in thread start ?
If you want to pass multiple values to a thread proc, you need to create an object to contain them. There are several ways to do that. The easiest is probably to use a Tuple:
for (Int32 i = 0; i < textBox8.Lines.Length; i++)
{
var thr1 = new Thread(testthr);
var data = new Tuple<string, string>(textBox8.Lines[i].Trim(), "hello");
thr1.Start(data);
thr.Add(thr1);
}
public void testthr(object state)
{
var data = (Tuple<string,string>)state;
var item1 = data.Item1;
var item2 = data.Item2;
...
}

running stored procedures into own model with servicestack ormlite

Is there any examples to be found for running a stored procedure on serviceStack MVC using ormlite? mythz ? seen this block of code:
var results = new List<EnergyCompare>
{dbFactory.Exec(dbCmd =>
{
dbCmd.CommandType = CommandType.StoredProcedure;
dbCmd.Parameters.Add(new SqlParameter("#id", 1));
dbCmd.CommandText = "GetAuthorById";
return dbCmd.ExecuteReader().ConvertTo<EnergyCompare>();
}
)};
but came with the text of never worked on the google groups!
i can also write this:
using(var db = new SwitchWizardDb())
{
var results2 = db.dbCmd.ExecuteProcedure()
}
but not sure how to complete this with parameters, and in the source code I looked at, it said obsolete?
thanks
Looks like ServiceStack.ORMLite has been updated to make this easier:
List<Poco> results = db.SqlList<Poco>("EXEC GetAnalyticsForWeek 1");
List<Poco> results = db.SqlList<Poco>("EXEC GetAnalyticsForWeek #weekNo", new { weekNo = 1 });
List<int> results = db.SqlList<int>("EXEC GetTotalsForWeek 1");
List<int> results = db.SqlList<int>("EXEC GetTotalsForWeek #weekNo", new { weekNo = 1 });
This example is on the front page of the github repo.
Well I figured it was best to roll my own handler so have created this, any thoughts would be most welcome, especially with how I could pass over params in some kind of func or something:
I have a main class to deal with easy access to my connection object:
public class DatabaseNameSp : IDisposable
{
private readonly SqlConnection _spConn = new SqlConnection(DatabaseNameSp .dbConString);
public readonly SqlCommand SpCmd;
public DatabaseNameSp (string procedureName)
{
_spConn.Open();
SpCmd = new SqlCommand
{
Connection = _spConn,
CommandType = CommandType.StoredProcedure,
CommandText = procedureName
};
}
public void Dispose()
{
_spConn.Close();
SpCmd.Dispose();
}
}
usage:
using (var db = new DatabaseNameSp ("procedurenname"))
{
db.SpCmd.Parameters.Add(new SqlParameter("#Id", 1));
var rdr = db.SpCmd.ExecuteReader(CommandBehavior.CloseConnection);
var results = new List<CustomDTO>();
while (rdr.Read())
{
results.Add(new CustomDTO { Name = rdr["name"].ToString(), Id = rdr["id"].ToString() });
}
return new CustomDTOResponse { Results = results };
}
Any thoughts !
thanks
Here is an example of running a stored procedure with ormLite that may help you:
IList<MyDTO> myList = DbFactory.Run(dbCnx =>
{
using (var dbCmd = dbCnx.CreateCommand())
{
dbCmd.CommandType = CommandType.StoredProcedure;
dbCmd.CommandText = "mySchema.myStoredProc";
dbCmd.Parameters.Add(new SqlParameter("#param1", val1));
dbCmd.Parameters.Add(new SqlParameter("#param2", val2));
var r = dbCmd.ExecuteReader();
return r.ConvertToList<MyDTO>();
}
});
To just simply run a stored procedure with no data returned:
public class ComsManager : Dbase
{
private IDbConnection dbConn;
public ComsManager()
{
dbConn = Dbase.GetConnection();
}
public void Housekeeping()
{
using(var dbCmd = dbConn.CreateCommand())
dbConn.Exec(res => { dbCmd.CommandType = CommandType.StoredProcedure; dbCmd.CommandText = "SP_housekeeping"; dbCmd.ExecuteNonQuery(); });
}

WCF - A newbie question about Tasks an WCF ;

this is the best approach for WCF inside tasks ?;
var tsk1 = Task.Factory.StartNew<list<object>>(()=> {
Mysvc svc1 = new Mysvc();
var t = svc1.getData();
scv1.Close();
return t;
});
var tsk2 = Task.Factory.StartNew<list<object>>(()=> {
Mysvc svc1 = new Mysvc();
var t2 = svc1.getData();
scv1.Close();
return t2;
});
Task.WaitALL(tsk1,tsk2);
var res = tsk1.Result;
var res2 = tsk2.Result;
Thnak you very much
If you have an asynchronous version of the contract (which, if you're using svcutil or add service reference, you can get by specifying the proper option), you can use the Task.Factory.FromAsync method to do that as well:
public class StackOverflow_6237996
{
[ServiceContract(Name = "ITest")]
public interface ITest
{
[OperationContract]
int Add(int x, int y);
}
[ServiceContract(Name = "ITest")]
public interface ITestAsync
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginAdd(int x, int y, AsyncCallback callback, object userState);
int EndAdd(IAsyncResult asyncResult);
}
public class Service : ITest
{
public int Add(int x, int y)
{
Thread.Sleep(100);
return x + y;
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITestAsync> factory = new ChannelFactory<ITestAsync>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
ITestAsync proxy = factory.CreateChannel();
var tsk1 = Task.Factory.FromAsync<int>(
proxy.BeginAdd(4, 5, null, null),
(ar) => proxy.EndAdd(ar));
var tsk2 = Task.Factory.FromAsync<int>(
proxy.BeginAdd(7, 8, null, null),
(ar) => proxy.EndAdd(ar));
Task.WaitAll(tsk1, tsk2);
Console.WriteLine("Result 1: {0}", tsk1.Result);
Console.WriteLine("Result 2: {0}", tsk2.Result);
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}

Resources