I have this code:
var a = 2;
I type using(...){} above declaration
Then I`m getting:
using(...)
{
}
var a = 2;
visual studio adds tab to a declaration. I want to prevent this, how I can achieve it ?
Edit: I added braces as I don`t want to have a inside using.
That is because the using statement executes codes whitin the scope the variable whitin the using exists. The correct syntax for using is:
using (var disposeMe = new DisposeMe())
{
// here you use the disposeMe object during its lifetime
var a = 2;
} // here disposeMe gets disposed.
With regards,
John
Related
This question already has answers here:
What is the C# Using block and why should I use it? [duplicate]
(9 answers)
Closed 2 years ago.
I am using System.Runtime.Caching to persist variables in cache, but later i cannot access to them because are disposed and the program throws a ObjectDisposedException with the message: DbContext has been disposed
I didn't execute Object.Dispose(), so the class ObjectCacheare disposing it in background.
In what moment at what moment does it happen? after doing cache.add?
It can be avoided?
How i made it:
Making the list:
using (GesBrokerSuiteEntities ctx = new GesBrokerSuiteEntities())
{
rel_tareas_orquestador nuevoregistroOrquestador = new rel_tareas_orquestador();
nuevoregistroOrquestador.id_robot_hija = idProyindividual;
nuevoregistroOrquestador.id_robot_padre = 2;
nuevoregistroOrquestador.id_robot_tarea_padre = "2";
nuevoregistroOrquestador.id_robot_tarea_hija = idProyindividual - 1+"";
nuevoregistroOrquestador.id_tarea_hija = Int32.Parse(id2);
nuevoregistroOrquestador.id_tarea_padre = 2;
nuevoregistroOrquestador.sincronizada = 2;
nuevoregistroOrquestador.esperar_padre_completa = 2;
ctx.rel_tareas_orquestador.Add(nuevoregistroOrquestador);
listaRelTareasOrquestador.Add(ctx);
1-Adding the list to cache
CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(1.0);
cache.Add("listaOrquestador", listObject, cacheItemPolicy);
2-Then i get it in another method
listaRelTareasOrquestador = (List<GesBrokerSuiteEntities>)cache.Get("listaOrquestador");
After this, i cannot access to the content of the list because it disposed.
UPDATE: withing the using() works, the elements aren't disposed.
now the problem us this, when trying to get the saved values, it obtains the database rows:
nuevoregistroOrquestador.id_robot_hija = listaRelTareasOrquestador[0].rel_tareas_orquestador.FirstOrDefault().id_robot_hija;
I know it is executing a query in my DB, any way to obtain the data i saved previously? Like a local variable.
UPDATE 2
Now when i'm trying to access the values into the list,i am not receving the previous ones:
rel_tareas_orquestador nuevoregistroOrquestador = new rel_tareas_orquestador();
nuevoregistroOrquestador.id_robot_hija = listaRelTareasOrquestador[0].rel_tareas_orquestador.FirstOrDefault().id_robot_hija;
nuevoregistroOrquestador.id_robot_padre = registro.rel_tareas_orquestador.FirstOrDefault().id_robot_padre;
nuevoregistroOrquestador.id_robot_tarea_padre = registro.rel_tareas_orquestador.FirstOrDefault().id_robot_tarea_padre;
nuevoregistroOrquestador.id_robot_tarea_hija = registro.rel_tareas_orquestador.FirstOrDefault().id_robot_tarea_hija;
I know the methods are returning database values due to querys, how i can access to the list values i saved previously?
Visual Studio shows me that in debugging:
It is disposed immediately after the closing bracket (if you mean a construction like this):
using (var reader = new StringReader(manyLines))
{
string? item;
do {
item = reader.ReadLine();
Console.WriteLine(item);
} while(item != null);
}
// reader disposed here
I want simply use io.py from C# to write a file and I use the following code:
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
...
System.IO.Directory.SetCurrentDirectory(
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) +
"\IronPython\Lib");
ScriptRuntime py = Python.CreateRuntime();
dynamic io = py.UseFile("io.py");
dynamic f = io.open("tmp.txt", "w");
f.writelines("some text...");
f.close();
but when I run the program the runtime give me a:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException telling that no overload of writelines accept argument '1'
it seems like that method doesn't exists... but into io.py documentation it exists.
P.S. The same is for close method!!!
Any idea?
I can only tell you how to make your code working, however I don't have much experience with IronPython and have no idea why it is done this way (though I try to learn that). First, it seems io module is treated in a special way and there is special (non-dynamic) class for that. When you do io.open what is returned is instance of PythonIOModule._IOBase class. You can do
var f = (PythonIOModule._IOBase) io.open("tmp.txt", "w");
And see for yourself that "writeline" method (which is regular method, not a dynamic one) accepts CodeContext instance as first argument, and second argument is lines. Interesting that this class itself already contains field with that CodeContext, but it is made internal for some reason, and what is even worse - writelines (and other methods) could have been using that CodeContext and not require us to provide external one. Why is it done like this - I have no idea.
So to make your code working, we have to get CodeContext somewhere. One way is do that via reflection:
var context = (CodeContext) f.GetType().GetField("context", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(f);
Another way is to craft it yourself:
var languageContext = HostingHelpers.GetLanguageContext(engine);
var context = new ModuleContext(io._io, new PythonContext(languageContext.DomainManager, new Dictionary<string, object>())).GlobalContext;
Both methods will work and program will successfully write to a file. Full working sample:
static void Main(string[] args) {
System.IO.Directory.SetCurrentDirectory(#"G:\Python27\Lib");
var engine = Python.CreateEngine();
dynamic io = engine.ImportModule("io");
var f = (PythonIOModule._IOBase) io.open("tmp.txt", "w");
var languageContext = HostingHelpers.GetLanguageContext(engine);
var context = new ModuleContext(io._io, new PythonContext(languageContext.DomainManager, new Dictionary<string, object>())).GlobalContext;
f.writelines(context, "some text....");
f.close(context);
}
I am trying to update the "ModifiedBy" field in a Sharepoint discussion board using the Client Object Model. By changing the "Editor" and "Author" fields, I can change the "ModifiedBy" that appears on the list view. However, once you click on a discussion post, the "ModifiedBy" field that appears there (the one with the picture above it) does not reflect the changes. After experimenting, I discovered that the field I need to change to correct this is called "MyEditor". Unfortunately, this field is read-only.
In the code below, I try to change the read-only settings of the field to false. When I look at the MyEditor field in Visual Studio's debugger after the ExecuteQuery() line at the bottom of the first block, it shows that the ReadOnlyField value has in fact been set to false.
sharepointContext.Load(discussionList);
sharepointContext.ExecuteQuery();
var fields = discussionList.Fields;
sharepointContext.Load(fields);
sharepointContext.ExecuteQuery();
var field = fields.GetByInternalNameOrTitle("MyEditor");
field.ReadOnlyField = false;
field.Update();
sharepointContext.Load(field);
sharepointContext.ExecuteQuery();
The code above executes with no problems. The problem comes with this next block:
//...Code to initialize discussionItem...
discussionItem["MyEditor"] = 0;
discussionItem["Editor"] = 0;
discussionItem["Author"] = 0;
discussionItem["Body"] = "Testing";
discussionItem["Title"] = "Hello Worlds";
discussionItem.Update();
sharepointContext.Load(discussionItem);
sharepointContext.ExecuteQuery();
When the code reaches the ExecuteQuery() at the bottom of the second block, it throws a ServerException with the following message:
Invalid data has been used to update the list item.
The field you are trying to update may be read only.
To make sure that the MyEditor field was the one causing the exception to be thrown, I commented out the line where I set it and ran the code again. Everything worked fine. I don't understand what is wrong, can someone help me?
In case someone needs to find the user by name, it goes like this:
private static FieldUserValue GetUser(ClientContext clientContext, string userName)
{
var userValue = new FieldUserValue();
var newUser = clientContext.Web.EnsureUser(userName);
clientContext.Load(newUser);
clientContext.ExecuteQuery();
userValue.LookupId = newUser.Id;
return userValue;
}
The returned value can be set via item["Author"]
ModifiedBy and CreadtedBy calculated automatically from Author and Editor you need to change only Author and Editor fields like this:
using (var clientContext = new ClientContext(#"http://server"))
{
var web = clientContext.Web;
var lst = web.Lists.GetByTitle("Discus");
var item = lst.GetItemById(2);
item["Author"] = 3;
item["Editor"] = 2;
item.Update();
clientContext.ExecuteQuery();
Console.WriteLine("done");
}
I am working with a C# project that uses the dll, Microsoft.Dynamics.AX.ManagedInterop to work with an AX 2012 environment. From within the code, I need to find a SalesQuotationLine based on specific criteria and delete it. So far, I can get the record I need but I am unable to delete it because I am not using a TTSBEGIN/TTSCOMMIT statement and I am not using FORUPDATE. This is my code:
DictTable dictTable = new DictTable(Global.tableName2Id("SalesQuotationLine"));
int quotationIdFieldId = (int)dictTable.Call("fieldName2Id", "QuotationId");
int bdcParentRecIdFieldId = (int)dictTable.Call("fieldName2Id", "BDCParentRecId");
var query = new Query();
var datasource = query.addDataSource(Global.tableName2Id("SalesQuotationLine"));
var queryRange1 = datasource.addRange(quotationIdFieldId);
queryRange1.value = "=" + line.QuotationId;
QueryRun queryRun = new QueryRun(query as object);
while (queryRun.next())
{
var result = queryRun.get(Global.tableName2Id("SalesQuotationLine"));
result.Delete();
}
I also looked at the code here, http://msdn.microsoft.com/en-us/library/cc197113.aspx but I found that I cannot use it since the code I am working with does not use the .NET Business Connector (I am not sure when one dll should be used over the other).
Use TTSBegin() and TTSCommit() methods on Microsoft.Dynamics.AX.ManagedInterop.RuntimeContext.Current. The forUpdate flag can be set by QueryBuildDataSource's update().
It may be easier (and better for maintenance) to write it in an X++ method just call the method from C#.
This thread is a continuation of Is there a reason to check for null inside multiple using clausule in c#?
I've noticed that resharper lets me define using without opening any opening/closing bracket like in the method below (but then i can't use defined vars later on if the brackets ain't there, other then the one that is used exactly beneath defined using):
public static string sqlGetDatabaseRows() {
string varRows = "";
const string preparedCommand = #"
SELECT SUM(row_count) AS 'Rows'
FROM sys.dm_db_partition_stats
WHERE index_id IN (0,1)
AND OBJECTPROPERTY([object_id], 'IsMsShipped') = 0;";
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP))
using (var sqlQuery = new SqlCommand(preparedCommand, varConnection))
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
while (sqlQueryResult.Read()) {
varRows = sqlQueryResult["Rows"].ToString();
}
sqlQueryResult.Close();
}
return varRows;
}
Is it good? Or should i use it like this?
public static string sqlGetDatabaseRows() {
string varRows = "";
const string preparedCommand = #"
SELECT SUM(row_count) AS 'Rows'
FROM sys.dm_db_partition_stats
WHERE index_id IN (0,1)
AND OBJECTPROPERTY([object_id], 'IsMsShipped') = 0;";
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP)) {
using (var sqlQuery = new SqlCommand(preparedCommand, varConnection))
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
while (sqlQueryResult.Read()) {
varRows = sqlQueryResult["Rows"].ToString();
}
sqlQueryResult.Close();
}
varConnection.Close();
}
return varRows;
}
sqlConnectOneTime looks like this:
public static SqlConnection sqlConnectOneTime(string varSqlConnectionDetails) {
SqlConnection sqlConnection = new SqlConnection(varSqlConnectionDetails);
sqlConnect(sqlConnection);
if (sqlConnection.State == ConnectionState.Open) {
return sqlConnection;
}
return null;
}
My questions are:
Should I be closing varConnection by using varConnection.Close() and sqlQueryResult.Close(); in the end? (but this enforces use of brackets) or will the connection close itself when using is done.
Should i be checking for NULL for varConnection since it's possible it will return null (on the other hand resharper doesn't complain here).
Is there some better approach i could use for defining sqlConnectOneTime ? Like when the connection fails to open it should return ConnectionState.Closed instead of null?
Also just on a note i open up new connection every time i execute new query / update / insert since i am using threading and it was the smartest idea i could come up at that very moment. Feel free to suggest better one :-)
I am asking about all this since i want to better understand whole process and stop making silly mistakes so be gentle with me.
MadBoy
Edit: modified question if varConnection.Close() and sqlQueryResult.Close() are nessecary if using is used.
Close() is called by the Dispose() method, so as long as you are using "using" properly you don't need to call Close() explicitly.
If it's possible for a NULL to be returned, you should check for it. I would advise that if you control the code that gets the sql connection, you strongly consider throwing an exception rather than returning NULL. Otherwise other developers may run into the same sorts of problems. Failure to open a SQL connection that is required seems to me to be a valid exceptional case. If necessary, you can always include a TryConnectOneTime for when a developer wants to avoid exception handling.
Also, another style note - I would advise properly bracing your using statements in case a stray extra line is added and an unexpected error occurs. Style-wise, I usually don't tend to indent using statements when I have multiple statements together, but that's all down to personal preference.
It's safe to use it like in the first example. using closes the reader, command and connection objects and even checks for null values (so you don't get a NullReferenceException if varConnection is null)