What I want to do is instead of sending Object { d : "{"FileID":"1213"}" } send "{"FileID":"1213"}"
My current code:
using System;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
[ScriptService]
partial class testing_class : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["FileID"] = Request.QueryString["FileID"];
}
public static string returnJSON(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public static string CurrentFile()
{
var d = new { FileID = "123" };
return returnJSON(d);
}
};
Microsoft stack Json serializers are pretty much obsolete and should be avoided at all costs. Instead you should be using (and newer .NET Web stack already is by default) Json.NET implementation.
If you don't have it installed you can do so by running Install-Package Newtonsoft.Json in your NuGet console window. Also make sure you are using Newtonsoft.Json;.
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public static string CurrentFile()
{
var d = new { FileID = "123" };
return JsonConvert.SerializeObject(d);
}
Related
I would like to ask for an idea how will I saved the data I retrieved from webservice. Here is what I have so far.
Everything is working. I was able to retrieve the data I needed from webservice but I don't have idea on how will I saved the data on my database.
cust.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp.Authenticators;
using System.IO;
using RestSharp;
using System.Text.Json;
using System.Data;
namespace SAP1
{
class cust
{
public class custOutput
{
public string NAME;
public string AGE;
public string ADD;
public DateTime DATE1;
public DateTime DATE2;
}
RestClient client;
RestRequest request;
public cust()
{
client = new RestClient(#"http://testwebservice/");
client.Authenticator = new HttpBasicAuthenticator("test1", "cust#Test1");
}
public List<custOutput>
GetcustOutputs(DateTime start, DateTime end)
{
request = new RestRequest("sap/bc/zcust", Method.Get);
request.AddParameter("sap-client", "200");
request.AddParameter("start","");
request.AddParameter("end", end.ToString("yyyyMMdd"));
var output = client.ExecuteAsync<List<custOutput>>(request);
var o = output.Result.Data;
return o;
}
public void ProcessOutput(DateTime start, DateTime end)
{
var output = GetcustOutputs(start, end);
Console.WriteLine(output.ToString());
// IEnumerable<DataRow> v = output.Select(x => new DataRow(x.NAME,));
}
}
}
This how I call my function.
form.cs
void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
_backgroundWorkerThread = Thread.CurrentThread;
SIAP svc = new SIAP();
cust cust = new cust();
cust.ProcessOutput(dte_from.Value, dte_to.Value);
}
catch (ThreadAbortException)
{
e.Cancel = true;
m_oWorker.Dispose();
Thread.ResetAbort();
}
}
I have a basic WinForm Solution (MS VS2013, .Net framework 4.5) for test some methods included in a Dll, using Reflection. My goal is test the main application that it can run two methods of Dll (without referencing the dll in project), and later, run four methods (2 methods added) without stop the main application and run it again, using reflection.
Reflections works fine (if I stop the main application, replacing the dll file and run the main application again, all works fine), but I can't replace the dll at runtime.
The main application has a Timer control with an interval of 60 seconds. Every 60 seconds, a method is executed that checks if a DLL file is in a folder. If a DLL file exists in that folder, I want to use the new DLL in the main application (running) because the new DLL contains old methods (first DLL) and additional methods that the main application needs.
However, I am getting an error that the file is in use.
I have read several posts, questions, answers, MEF documentation, AppDomains related, but I have been unable to concatenate the information to be able to implement a solution.
Actually, I thought a lot before post this question, but I confess that I prefer to spend a moment of shame, knowing that you can give me a hand.
It would be for me a great help if you help me with code and specific instructions.
This is the code:
Main application:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
namespace testDLLs
{
public partial class Principal : Form
{
public Principal()
{
InitializeComponent();
}
private void Principal_Load(object sender, EventArgs e)
{
labelVersionDll.Text = metodosApoyo.RunDLLFunction("VersionOperaciones");
string cListaOperaciones = metodosApoyo.RunDLLFunction("ListaOperaciones");
string[] aOperaciones = cListaOperaciones.Split('|');
comboBoxOperaciones.Items.Clear();
foreach (string cOperacion in aOperaciones)
{
comboBoxOperaciones.Items.Add(cOperacion);
}
timerForUpdate.Interval = 60000;
timerForUpdate.Enabled = true;
}
private void buttonRun_Click(object sender, EventArgs e)
{
int iOperador1, iOperador2;
string resultadoDesdeDll = null;
string cOperacionSeleccionada;
Int32.TryParse(textBoxOperador1.Text, out iOperador1);
Int32.TryParse(textBoxOperador2.Text, out iOperador2);
cOperacionSeleccionada = comboBoxOperaciones.GetItemText(comboBoxOperaciones.SelectedItem);
object[] parametersArray = new object[] { iOperador1, iOperador2 };
resultadoDesdeDll = metodosApoyo.RunDLLFunction(cOperacionSeleccionada, parametersArray);
textBoxResultado.Text = resultadoDesdeDll;
}
private void timerForUpdate_Tick(object sender, EventArgs e)
{
labelUpdateStatus.Text = "Checking updates ...";
notifyIconUpdate.Visible = true;
notifyIconUpdate.BalloonTipText = "Instalando nuevo DLL....";
notifyIconUpdate.BalloonTipTitle = "Info:";
notifyIconUpdate.ShowBalloonTip(5000);
if (File.Exists(#"C:\DLLsForCopy\OperacionesDLL.dll"))
{
File.Copy(#"C:\DLLsForCopy\OperacionesDLL.dll", #"D:\DLLs\OperacionesDLL.dll", true);
labelVersionDll.Text = metodosApoyo.RunDLLFunction("VersionOperaciones");
string cListaOperaciones = metodosApoyo.RunDLLFunction("ListaOperaciones");
string[] aOperaciones = cListaOperaciones.Split('|');
comboBoxOperaciones.Items.Clear();
foreach (string cOperacion in aOperaciones)
{
comboBoxOperaciones.Items.Add(cOperacion);
}
}
labelUpdateStatus.Text = "";
notifyIconUpdate.Visible = false;
}
}
}
Class in project, for some functions for Main application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace testDLLs
{
class metodosApoyo
{
public static string RunDLLFunction(string cMetodo, object[] aParametros = null)
{
string cRetornoGlobal = "";
Object resultado = null;
string cOperacionSeleccionada = cMetodo;
Assembly assembly = Assembly.LoadFile(#"D:\DLLs\OperacionesDLL.dll");
Type type = assembly.GetType("OperacionesDLL.Operaciones");
MethodInfo methodInfo = type.GetMethod(cOperacionSeleccionada);
ParameterInfo[] parameters = methodInfo.GetParameters();
object classInstance = Activator.CreateInstance(type, null);
object[] parametersArray = null;
if (aParametros != null)
{
parametersArray = new object[aParametros.Length];
int i = 0;
foreach (object value in aParametros)
{
parametersArray[i] = aParametros[i];
i++;
}
}
resultado = methodInfo.Invoke(methodInfo, parametersArray);
cRetornoGlobal = (string)resultado;
return cRetornoGlobal;
}
}
}
DLL source (OperacionesDLL.dll):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OperacionesDLL
{
public class Operaciones
{
public static string VersionOperaciones()
{
string retorno;
retorno = "1.0701-16";
return retorno;
}
public static string ListaOperaciones()
{
string retorno;
retorno = "Suma|Resta|Multiplicación|División";
return retorno;
}
public static string Suma(int operador1, int operador2)
{
int resultado;
string retorno;
resultado = operador1 + operador2;
retorno = resultado.ToString();
return retorno;
}
public static string Resta(int operador1, int operador2)
{
int resultado;
string retorno;
resultado = operador1 - operador2;
retorno = resultado.ToString();
return retorno;
}
public static string Multiplicación(int operador1, int operador2)
{
int resultado;
string retorno;
resultado = operador1 * operador2;
retorno = resultado.ToString();
return retorno;
}
public static string División(int operador1, int operador2)
{
int resultado;
string retorno;
resultado = operador1 / operador2;
retorno = resultado.ToString();
return retorno;
}
}
}
Thanks in advance.
You can do what you're describing by using the Managed Addin Framework (MAF) in the System.Addin namespace. I've used it to write apps that scans a folder for DLLs and dynamically loads them. You can also use it to unload and reload DLLs as they appear and disappear from the folder.
Even using an example from the Documentation, I still can't find a way to successfully serialize to a file.
Code:
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
using System.Threading;
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
Item i = new Item
{
Username = "user",
Email = "user#user.com",
Password = "password"
};
File.WriteAllText(#"C:\users\user1.json", JsonConvert.SerializeObject(i));
using (StreamWriter file = File.CreateText(#"C:\users\user1.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, i);
}
}
}
}
Item.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestProject
{
public class Item
{
public string Email { get; set; }
public string Password { get; set; }
public string Username { get; set; }
}
}
When I run Program.cs, it shows no errors, but the JSON does not show in the file.
When I run your code I get a an exception writing to the users folder. Changing to my home folder works fine. I suspect this is your problem.
Addtionally, you're writing the file twice. The first time is showing an example of using the SerializeObject method to get a string back which is used with WriteAllText. The second block of code is using a StreamWriter. For your purposes, both are equivalent and you only need to use one or the other.
using (StreamWriter file = File.CreateText(#"C:\users\user1.json"))
{
var jsonResult = JsonConvert.SerializeObject(i);
file.WriteLine(jsonResult);
}
I have a promblem with run-time compiled classes. I have something like this 2 classes:
first class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program.Bullet {
public class Class1{
private int i;
public Class1(int j){
i=j;
}
}
}
and second class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Program.Bullet;
namespace Program.Object {
public class Class2{
public Class2(){
Class1 c1 = new Class1(5);
}
}
}
This two classes I would like to compile in run-time and use them in my project. So I have function to compile it (XmlNode has data about fullPath etc):
private ModuleBuilder moduleBuilder;
private List<string> isCompiled;
private void Compile(XmlNode compileingClasses) {
foreach (XmlNode compileingClass in compileingClasses) {
string fullPath = compileingClass.Attributes["path"].InnerText;
string type = compileingClass.Attributes["name"].InnerText; ;
if (!isCompiled.Contains(type)) {
isCompiled.Add(type);
var syntaxTree = SyntaxTree.ParseFile("../../File1/File2/" + fullPath);
var comp = Compilation.Create("Test.dll"
, syntaxTrees: new[] { syntaxTree }
, references: metadataRef
, options: comilationOption
);
// Runtime compilation and check errors
var result = comp.Emit(moduleBuilder);
if (!result.Success) {
foreach (var d in result.Diagnostics) {
Console.WriteLine(d);
}
throw new XmlLoadException("Class not found " + fullPath);
}
}
}
}
Is it possible to get the reference on Class1 to Class2?
Edit: Better question
Is it possible to create MetadataReference on compiled Class1?
Something like:
string fullName = bullet.Attributes["fullName"].InnerText;
var o = moduleBuilder.GetType(fullName);
metadataRef.Add(new MetadataFileReference(o.Assembly.Location));
This throw NotSupportedException
You're trying to reference the assembly which is currently being built and I don't think Roslyn can do that.
What you can do instead is to create a single Compilation from all your classes (probably having a separate SyntaxTree for each class). If you do that, you won't need any references.
How to pass a class into another class to a codebehind?
When I debug and check the myCategoryObj in the Default.aspx page, I can see the object is in the debug. What am I doing wrong?
I know I could create the object in the Default.aspx but I should not have to I should be able to call the Business Logic Layer and ask for an object back and then fill the object and pass it back to the Business Logic Layer to be saved (insert or update).
I hope this makes sense.
Default.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SC1.Models.OBJ;
using SC1.Models.BLL;
using SC1.Models.DAL;
namespace SC1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(Object sender, EventArgs e)
{
// I know I could do this but I don't want to unless I have too.
//Category categoryObj = new Category();
CategoryBLL myCategoryBLL = new CategoryBLL();
Object myCategoryObj = myCategoryBLL.CategoryNew();
// How do I make the code below work or what am I doing wrong.
myCategoryObj.Name = "test";
string test = "";
}
}
}
CategoryBLL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using SC1.Models.DAL;
using SC1.Models.OBJ;
namespace SC1.Models.BLL
{
public class CategoryBLL
{
// Create a page object
Category myCategoryObject = new Category();
// Create a Data Acces Layer Object
CategoryDAL myCategoryDAL = new CategoryDAL();
public CategoryBLL()
{
}
public DataSet Select()
{
return (myCategoryDAL.Select());
}
public Object CategoryNew()
{
return myCategoryObject;
}
}
}
CategoryDAL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace SC1.Models.DAL
{
public class CategoryDAL
{
public CategoryDAL()
{
}
string connStr = ConfigurationManager.ConnectionStrings["staceys_cakesConnectionString"].ConnectionString;
// select all
public DataSet Select()
{
SqlConnection sqlConnection1 = new SqlConnection();
string SqlString = "select * from Categories";
SqlDataAdapter da = new SqlDataAdapter(SqlString, connStr);
DataSet ds = new DataSet();
da.Fill(ds, "Categories");
return (ds);
}
// save
// insert
// update
// delete
}
}
Category.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SC1.Models.OBJ
{
public class Category
{
public int CategoryID { get; set; }
public int ParentID { get; set; }
public string Name { get; set; }
public int DisplayOrder { get; set; }
public bool Active { get; set; }
public Category(){
}
}
}
change
Object myCategoryObj = myCategoryBLL.CategoryNew()
to
Category myCategoryObj = myCategoryBLL.CategoryNew()
and also
public Object CategoryNew()
{
return myCategoryObject;
}
to
public Category CategoryNew()
{
return myCategoryObject;
}