ASP.Net Calling method from another namespace - c#

I have two projects, the first one with a ClassLibraryServer namespace and Output method as following :
namespace ClassLibraryServer
{
public class Output
{
public static void Card(tblCard card, int myProperty)
{
if (kort.fltNr.Length != 6)
return;
using (myDataContext db = new myDataContext(ClassLibrary.Settings.Instance.SqlS))
{
tblReader[] readers = (from row in db.tblReader
where !row.fltOffline
select row).ToArray();
bool blocked = (db.tblCardBlocked.Where(b => b.fltProperty == myProperty && b.fltCard == card.id).FirstOrDefault() != null);
foreach (tblReader reader in readers)
{
Card(card, reader, blocked);
}
}
}
}
}
The Card method in foreach loop calls another method (Overloading the first card method) which has three parameters and inserts data to a sql table, I won't share it here as it takes too much space.
Now I want to call above method in another project with namespace ExtControlModule:
namespace ExtControlModule
{
public class TimeModule
{
using (ModuleDataContext dbsys = new ModuleDataContext(ClassLibrary.Settings.Instance.SqlS)) {
var loungee = (from tblLounge in dbsys.tblLounges
select tblLounge).ToList();
var lasaresFas = 0;
foreach (var LoungeRow in loungee)
{
lasaresFas= Convert.ToInt32(dbsys.tblLasares.FirstOrDefault(f => f.id == LoungeRow.fltCardreader).fltproperty);
tblCard cardLoading = dbsys.tblCard.FirstOrDefault(t => t.id == res.fltCardnumber);
Output.Card(cardLoading, lasaresFas);
}
}
}
Now when I want to assign parameters to Output.Card in ExtControlModule I get the following error in cardLoading parameter in Output.Card:
Argument !: cannot convert from 'ExtControlModule.tblCard' to ClassLibrary.db.tblCard'
ClassLibrary is another project in the same Solution which contains a public class Settings with the SqlS property which facilitate connection to SQL database.
Struggling with this for many days as I am new to both ASP.NET and Sql, hope my question is clear enough.

call method
ClassLibraryServer.Output.Card(cardLoading, lasaresFas);

Related

DbSet.Remove() seems like to remove sometimes

Hello I have this project on Entity Framework for an exam, I have 157 test to pass and I pass 155, the last 2 are very similar to others but I dont understand why fails, I put some code so I can explain better:
public void GetUsers_OnDeletedObject_Throws() {
Site.Delete();
Assert.That(() => Site.GetUsers(), Throws.TypeOf<InvalidOperationException>()); }
I defined the Delete() method to recorsively call Delete to resources in the site(like users), then remove the site from the context.
From now on any method in the site must throw InvalidOperationException because the site doesn't exist anymore, but in some way Site.GetUsers() find a site and dont throw.
The real mistery is if I try to insert other methods (written in same way) between the delete and the assert the extra method throw InvalidOperationException!
Site.Delete() code:
using (var ctx = new SiteContext(connectionString))
{
var site = ctx.Sites.Find(Name);
foreach (var a in GetAuctions()) ctx.Auctions.Remove(a);
foreach (var s in GetSessions()) ctx.Sessions.Remove(s);
foreach (var u in GetUsers()) ctx.Users.Remove(u);
ctx.Sites.Remove(site);
ctx.SaveChanges();
}
Part of GetUsers where should throw
public IEnumerable<IUser>GetUsers()
{
using (var ctx = new SiteContext(connectionString))
{
var site = ctx.Sites.SingleOrDefault(s => s.Name == Name);
AlreadyDeleted(site);
AlreadyDeleted() code:
public static void AlreadyDeleted(object o)
{
if (null == o) throw new InvalidOperationException();
}

How to access and modify a node with code fix provider from another node

I have a situation where I need to modify a situation where a user writes this kind of code :
bool SomeMethod(object obj)
{
if(obj == null)
return false;
return true;
}
To the following code :
bool SomeMethod(object obj)
{
return obj == null;
}
Currently, I have built an analyzer that works. I'll put the code below. Basically, the analyzer looks for if statements and verifies if the only statement of the if is a return statement.Not only that, it verifies that also, the next statement inside the method's declaration is a return statement.
The code fix provider looks for the ifStatement's condition and creates a new return statement using that condition. What I'm trying to do after replacing the if statement by the return statement, is to remove the second return statement. At this, I'm failing without knowing how.
At first, when the node's been replaced, I create a new root, because they can't be modify like a string, it's about the same thing. I try to delete the node, but this instruction is being ignored for some reason. And I've debugged it, when I access the next node(ReturnStatement), it's not null.
I guess my question is basically, how can I build a code fix provider which can modify a node without being "linked" on it.
Here's the code for the analyzer
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using System.Linq;
namespace RefactoringEssentials.CSharp.Diagnostics
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class RewriteIfReturnToReturnAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
CSharpDiagnosticIDs.RewriteIfReturnToReturnAnalyzerID,
GettextCatalog.GetString("Convert 'if...return' to 'return'"),
GettextCatalog.GetString("Convert to 'return' statement"),
DiagnosticAnalyzerCategories.Opportunities,
DiagnosticSeverity.Info,
isEnabledByDefault: true,
helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RewriteIfReturnToReturnAnalyzerID)
);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(
(nodeContext) =>
{
Diagnostic diagnostic;
if (TryGetDiagnostic(nodeContext, out diagnostic))
{
nodeContext.ReportDiagnostic(diagnostic);
}
}, SyntaxKind.IfStatement);
}
private static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
{
diagnostic = default(Diagnostic);
if (nodeContext.IsFromGeneratedCode())
return false;
var node = nodeContext.Node as IfStatementSyntax;
var methodBody = node?.Parent as BlockSyntax;
var ifStatementIndex = methodBody?.Statements.IndexOf(node);
if (node?.Statement is ReturnStatementSyntax &&
methodBody?.Statements.ElementAt(ifStatementIndex.Value + 1) is ReturnStatementSyntax)
{
diagnostic = Diagnostic.Create(descriptor, node.GetLocation());
return true;
}
return false;
}
}
}
Here's the code for the Code fix provider
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
namespace RefactoringEssentials.CSharp.Diagnostics
{
[ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared]
public class RewriteIfReturnToReturnCodeFixProvider : CodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds
{
get
{
return ImmutableArray.Create(CSharpDiagnosticIDs.RewriteIfReturnToReturnAnalyzerID);
}
}
public override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public async override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var cancellationToken = context.CancellationToken;
var span = context.Span;
var diagnostics = context.Diagnostics;
var root = await document.GetSyntaxRootAsync(cancellationToken);
var diagnostic = diagnostics.First();
var node = root.FindNode(context.Span);
if (node == null)
return;
context.RegisterCodeFix(
CodeActionFactory.Create(node.Span, diagnostic.Severity, "Convert to 'return' statement", token =>
{
var statementCondition = (node as IfStatementSyntax)?.Condition;
var newReturn = SyntaxFactory.ReturnStatement(SyntaxFactory.Token(SyntaxKind.ReturnKeyword),
statementCondition, SyntaxFactory.Token(SyntaxKind.SemicolonToken));
var newRoot = root.ReplaceNode(node as IfStatementSyntax, newReturn
.WithLeadingTrivia(node.GetLeadingTrivia())
.WithAdditionalAnnotations(Formatter.Annotation));
var block = node.Parent as BlockSyntax;
if (block == null)
return null;
//This code (starting from here) does not do what I'd like to do ...
var returnStatementAfterIfStatementIndex = block.Statements.IndexOf(node as IfStatementSyntax) + 1;
var returnStatementToBeEliminated = block.Statements.ElementAt(returnStatementAfterIfStatementIndex) as ReturnStatementSyntax;
var secondNewRoot = newRoot.RemoveNode(returnStatementToBeEliminated, SyntaxRemoveOptions.KeepNoTrivia);
return Task.FromResult(document.WithSyntaxRoot(secondNewRoot));
}), diagnostic);
}
}
}
And finally, this is my NUnit test :
[Test]
public void When_Retrurn_Statement_Corrected()
{
var input = #"
class TestClass
{
bool TestMethod (object obj)
{
$if (obj != null)
return true;$
return false;
}
}";
var output = #"
class TestClass
{
bool TestMethod (object obj)
{
return obj!= null;
}
}";
Analyze<RewriteIfReturnToReturnAnalyzer>(input, output);
}
I believe the problem is probably this line:
var block = node.Parent as BlockSyntax;
You're using the node from the original tree, with a .Parent also from the original tree (not the one with the updated newReturn).
Then, it eventually calculates returnStatementToBeEliminated using this old tree that's no longer up-to-date, so when you call var secondNewRoot = newRoot.RemoveNode(returnStatementToBeEliminated, SyntaxRemoveOptions.KeepNoTrivia);, nothing happens because newRoot does not contain returnStatementToBeEliminated.
So, you basically want to use the equivalent of node.Parent, but the version that lives under newRoot. The low-level tool we use for this is called a SyntaxAnnotation, and these have the property that they track forward between tree edits. You can add a specific annotation to the node.Parent before making any edits, then make your edits, and then ask the newRoot to find the node with your annotation.
You can track nodes manually like this, or you can use the SyntaxEditor class, which abstracts the Annotations part away into simpler methods like TrackNode (there's a few other nice features in SyntaxEditor that you may want to check out).
For this issue, I was refer to the following post :
How do I create a new root by adding and removing nodes retrieved from the old root?
This post showed this class called DocumentEditor, which lets a user modify a document like he wants even though it's suppose to be immutable. The previous issue was that after deleting a node, if I was referring something that had a connection to that node, the relation would have disappear and I would be able to stuff.
Basically, the documentation comment says that this class is "an editor for making changes to a document's syntax tree."
After you're done modifying that document, you need to create a new document and return it as a Task in the code fix provider.
To solve this issue I had with my code fix provider, I used the following code :
context.RegisterCodeFix(CodeAction.Create("Convert to 'return' statement", async token =>
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken);
var statementCondition = (node as IfStatementSyntax)?.Condition;
var newReturn = SyntaxFactory.ReturnStatement(SyntaxFactory.Token(SyntaxKind.ReturnKeyword),
statementCondition, SyntaxFactory.Token(SyntaxKind.SemicolonToken));
editor.ReplaceNode(node as IfStatementSyntax, newReturn
.WithLeadingTrivia(node.GetLeadingTrivia())
.WithAdditionalAnnotations(Formatter.Annotation));
var block = node.Parent as BlockSyntax;
if (block == null)
return null;
var returnStatementAfterIfStatementIndex = block.Statements.IndexOf(node as IfStatementSyntax) + 1;
var returnStatementToBeEliminated = block.Statements.ElementAt(returnStatementAfterIfStatementIndex) as ReturnStatementSyntax;
editor.RemoveNode(returnStatementToBeEliminated);
var newDocument = editor.GetChangedDocument();
return newDocument;
}, string.Empty), diagnostic);
It was really simple to solve my issue thanks to that class.

Creating a plan repository, but using keyword in constructor body

I have a class that needs to access the planInfo LINQ variable in every method. Is there any way to do this without removing the using statement and calling Dispose() in every method?
The only other way I know to do it is to put the using statement in every method and removing it from the constructor, but that is repeating the where clause in every method but i want it constant.
public class PlanRepository
{
private int _patientId = 0;
private IQueryable<Plan> planInfo;
public PlanRepository(int pid)
{
if (pid == 0) { UserAccess.RedirectToLogin(); }
_patientId = pid;
using (var db = new DbConn())
{
planInfo = db.Plans.Where(d => d.PatientId == _patientId);
}
}
public int GetPulse()
{
return planInfo.Select(d => d.Pulse).FirstOrDefault();
}
}
This code obviously throws an error that the db connection was closed.
Just materialize the list in the constructor:
planInfo = db.Plans.Where(d => d.PatientId == _patientId).ToList();
Now, that caches the data (you won't see any DB updates), but if you didn't want to maintain the DB connection in the first place, that shouldn't be an issue.
With the list materialized, all your other functions can use it with no problem.

SmartThreadPool - Is it possible to pass delegate method with method parameters?

I have a long running process called ImportProductInformation called by a consoleapp that I'm trying to speed up, which appears to be an excellent candidate for thread-pooling, so I did a little searching and came across SmartThreadPool on CodeProject and am trying to implement it.
ImportProductInformation currently requires an "item", which is just a single entity-framework row pulled from a list. SmartThreadPool uses a delegate called "WorkItemCallback", but if I build it like below it complains about "Method name expected" in the foreach loop on smartThreadPool.QueueWorkItem, as it appears I can't pass my params to the delegated method. What am I missing here? I'm sure it's something stupid...noob lacking experience with delegates...any help would be appreciated:
public static void ImportProductInformation_Exec()
{
// List
List<productinformation> _list = GetProductInformation();
// Import
if (_list != null)
{
SmartThreadPool smartThreadPool = new SmartThreadPool();
foreach (var item in _list)
{
smartThreadPool.QueueWorkItem
(new WorkItemCallback
(ImportProductInformation(item)));
}
smartThreadPool.WaitForIdle();
smartThreadPool.Shutdown();
}
}
public void ImportProductInformation(productinformation item)
{
// Do work associated with "item" here
}
If I change the loop to this I get "Method is used like a Type" in the build error:
foreach (var item in _list)
{
ImportProductInformation ipi =
new ImportProductInformation(item);
smartThreadPool.QueueWorkItem(new WorkItemCallback(ipi));
}
Ended up getting it to work with this:
public class ProductInformationTaskInfo
{
public productinformation ProductInformation;
public ProductInformationTaskInfo(productinformation pi)
{
ProductInformation = pi;
}
}
public class PI
{
foreach (var item in _list)
{
ProductInformationTaskInfo pi =
new ProductInformationTaskInfo(item);
smartThreadPool.QueueWorkItem
(new WorkItemCallback
(ImportProductInformation), pi);
}
public static object ImportProductInformation(Object _pi)
{
ProductInformationTaskInfo pi = (ProductInformationTaskInfo)_pi;
var item = pi.ProductInformation;
// Do work here
}
}
I don't know or have the SmartThreadPool, the following is approximate:
foreach (var item in _list)
{
var itemCopy = item;
smartThreadPool.QueueWorkItem
(dummy => ImportProductInformation(itemCopy));
}
You may have to do some fixing.
This works because the lambda captures a variable from the containing method. And that's why you need itemCopy.
But note that the normal ThreadPool is not suited for longrunning tasks, the same may hold for the SmartThreadPool. It should also keep a limit on the number of threads, and when ImportProductInformation does mainly I/O threading might not help at all.
You can use anonymous methods:
int a = 15;
String b = "hello world!";
ThreadPool.QueueUserWorkItem((state)=>SomeFunction(a,b));

How can I change the table adapter's command timeout

I'm using Visual Studio 2008 with C#.
I have a .xsd file and it has a table adapter. I want to change the table adapter's command timeout.
Thanks for your help.
With some small modifications csl's idea works great.
partial class FooTableAdapter
{
/**
* <summary>
* Set timeout in seconds for Select statements.
* </summary>
*/
public int SelectCommandTimeout
{
set
{
for (int i = 0; i < this.CommandCollection.Length; i++)
if (this.CommandCollection[i] != null)
this.CommandCollection[i].CommandTimeout = value;
}
}
}
To use it, just set
this.FooTableAdapter.CommandTimeout = 60; somewhere before the this.FooTableAdapter.Fill();
If you need to change the timeout on a lot of table adapters, you could create a generic extension method and have it use reflection to change the timeout.
/// <summary>
/// Set the Select command timeout for a Table Adapter
/// </summary>
public static void TableAdapterCommandTimeout<T>(this T TableAdapter, int CommandTimeout) where T : global::System.ComponentModel.Component
{
foreach (var c in typeof(T).GetProperty("CommandCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Instance).GetValue(TableAdapter, null) as System.Data.SqlClient.SqlCommand[])
c.CommandTimeout = CommandTimeout;
}
Usage:
this.FooTableAdapter.TableAdapterCommandTimeout(60);
this.FooTableAdapter.Fill(...);
This is a little slower. And there is the possibility of an error if you use it on the wrong type of object. (As far as I know, there is no "TableAdapter" class that you could limit it to.)
I have investigated this issue a bit today and come up with the following solution based on a few sources.
The idea is to create a base class for the table adapter too inherit which increases the timeout for all commands in the table adapter without having to rewrite too much existing code. It has to use reflection since the generated table adapters don't inherit anything useful. It exposes a public function to alter the timeout if you want to delete what i used in the constructor and use that.
using System;
using System.Data.SqlClient;
using System.Reflection;
namespace CSP
{
public class TableAdapterBase : System.ComponentModel.Component
{
public TableAdapterBase()
{
SetCommandTimeout(GetConnection().ConnectionTimeout);
}
public void SetCommandTimeout(int Timeout)
{
foreach (var c in SelectCommand())
c.CommandTimeout = Timeout;
}
private System.Data.SqlClient.SqlConnection GetConnection()
{
return GetProperty("Connection") as System.Data.SqlClient.SqlConnection;
}
private SqlCommand[] SelectCommand()
{
return GetProperty("CommandCollection") as SqlCommand[];
}
private Object GetProperty(String s)
{
return this.GetType().GetProperty(s, BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance).GetValue(this, null);
}
}
}
I had a couple of issues with using Mitchell Gilman's solution that I was eventually able to workaround.
First of all, I needed to make sure to use the right namespace. It took me a while to figure out that Designer file for the xsd data set actually contains two namespaces, one for the data set in general and one for the table adapters. So the first thing is to note is that the namespace for the table adapter should be used, not for the data set in general.
Secondly, the commandcollection may not always be initialized when the timeout command is used for the first time. To work around this, I called the InitCommandCollection command if this was the case.
So the adapted solution I used was
namespace xxx.xxxTableAdapters
partial class FooTableAdapter
{
/**
* <summary>
* Set timeout in seconds for Select statements.
* </summary>
*/
public int SelectCommandTimeout
{
set
{
if (this.CommandCollection == null)
this.InitCommandCollection();
for (int i = 0; i < this.CommandCollection.Length; i++)
if (this.CommandCollection[i] != null)
this.CommandCollection[i].CommandTimeout = value;
}
}
}
Hope that's helpful to people!
In some cases you cannot access members like Adapter in your class, since they are defined as private to the class.
Fortunately, the wizard will generate partial classes, which means you can extend them. As described in [this thread by Piebald][1], you can write your own property to set the timeout on select-commands.
Generally, you would do this:
partial class FooTableAdapter
{
/**
* <summary>
* Set timeout in seconds for Select statements.
* </summary>
*/
public int SelectCommandTimeout
{
set
{
for ( int n=0; n < _commandCollection.Length; ++n )
if ( _commandCollection[n] != null )
((System.Data.SqlClient.SqlCommand)_commandCollection[n])
.commandTimeout = value;
}
}
}
Note that I have not actually tried this myself, but it seems like a viable solution.
Say your dataset is called MySET.
There is one table called MyTable
MySETTableAdapters.MyTableTableAdapter fAdapter =
new MySETTableAdapters.MyTableTableAdapter();
fAdapter.Adapter.SelectCommand.CommandTimeout = <fill inyour value here>;
Call ChangeTimeout Function by providing the TableAdapter and Time in seconds.
this.ChangeTimeout(this.taTest, 500);
Function :
private void ChangeTimeout(Component component, int timeout)
{
if (!component.GetType().FullName.Contains("TableAdapter")) {
return;
}
PropertyInfo adapterProp = component.GetType().GetProperty("CommandCollection", BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance);
if (adapterProp == null) {
return;
}
SqlCommand[] command = adapterProp.GetValue(component, null) as SqlCommand[];
if (command == null) {
return;
}
Interaction.command(0).CommandTimeout = timeout;
}
Here's some example code from MSDN, using VB.NET:
Imports System.Data.SqlClient
Namespace MyDataSetTableAdapters
Partial Class CustomersTableAdapter
Public Sub SetCommandTimeOut(ByVal timeOut As Integer)
For Each command As SqlCommand In Me.CommandCollection
command.CommandTimeout = timeOut
Next
End Sub
End Class
End Namespace
When it comes time to call a long query, just call the SetCommandTimeOut method before the query:
Dim ds As New MyDataSet
Dim customersTA As New MyDataSetTableAdapters.CustomersTableAdapter
' Increase time-out to 60 seconds
customersTA.SetCommandTimeOut(60000)
' Do the slow query
customersTA.FillSlowQuery(ds.Customers)
There seems to be a more convenient way to do this. Here's a quick recap of what I found.
Let's say I add a (class library) project called MyDB to my solution. Into that project I add a DataSet called "Data". And into that dataset, I drag a table called "X".
What I get on the design surface is an object that shows that I have an object called "XTableAdapter".
I now open the generated code, Data.Designer.cs, and look for XTableAdapter.
When I find it, I note that it's contained in namespace MyDB.DataTableAdapters - which is just a concatenation of the name of the project, "MyDB", the name of the DataSet, "Data", and "TableAdapters".
With that in hand, I now go back to the class library, still called Class1.cs (which I'll ignore for now).
I change its namespace from MyDB to MyDB.DataTableAdapters.
I change the class declaration to public partial class XTableAdapter,
and make it look like this:
using System.Data.SqlClient;
namespace MyDB.DataTableAdapters
{
public partial class XTableAdapter
{
public void SetTimeout(int seconds)
{
foreach (SqlCommand cmd in CommandCollection)
{
cmd.CommandTimeout = seconds;
}
}
}
}
The calling sequence could hardly be clearer:
int TwoMinutes = 120;
XTableAdapter.SetTimeout(TwoMinutes);
Less muss, less fuss, less reflection (well, none), less filling.
If you use a partial class, make you have the right namespace. Probably [your data set's name] + "TableAdapters'. Example:
namespace MyProject.DataSet1TableAdapters
You can open up the Properties folder, open Settings.settings and alter the Timeout property of your connection string.
This one is a bit old now and suspect this solution is not relevant to everyone, but I've ended up using AniPol's solution to override the ObjectDataSource control as follows:
public class MyObjectDataSource : ObjectDataSource
{
public MyObjectDataSource()
{
this.ObjectCreated += this.MyObjectDataSource_ObjectCreated;
}
private void MyObjectDataSource_ObjectCreated(object sender, ObjectDataSourceEventArgs e)
{
var objectDataSourceView = sender as ObjectDataSourceView;
if (objectDataSourceView != null && objectDataSourceView.TypeName.EndsWith("TableAdapter"))
{
var adapter = e.ObjectInstance;
PropertyInfo adapterProp = adapter.GetType()
.GetProperty(
"CommandCollection",
BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance);
if (adapterProp == null)
{
return;
}
SqlCommand[] commandCollection = adapterProp.GetValue(adapter, null) as SqlCommand[];
if (commandCollection == null)
{
return;
}
foreach (System.Data.SqlClient.SqlCommand cmd in commandCollection)
{
cmd.CommandTimeout = 120;
}
}
}
}
I do like this ; Right click Fill() or GetX() function and click Goto Defination from menu.
You will see Source code of DATATABLE. And find ;
private global::System.Data.SqlClient.SqlCommand[] _commandCollection;
command line from your dataadapter class.
And Change the private to public .
Now you can access the _commandCollection and you can change all attributes.
But be careful when you add or change any Filed form DESIGNER , the public will be private again by autogenerate system.
And also , when you finish to call Fill or Get Function you must reset _commandColleciton calling this function ( InitCommandCollection() )
public void InitCommandCollection() {}
This function is also private by autogen, you must change to public also!
Example:
dsIslemlerTableAdapters.tblIslemlerTableAdapter _t = new dsIslemlerTableAdapters.tblIslemlerTableAdapter();
dsIslemler.tblIslemlerDataTable _m = new dsIslemler.tblIslemlerDataTable();
_t._commandCollection[0].CommandText = "Select * From tblIslemler Where IslemTarihi>='' And IslemTarihi<=''";
_m = _t.GetData();
_t.InitCommandCollection();
Expanding on the already very useful answers for tableadapters that helped me a lot, I also had the need to read out the actual timeout value. Thus:
namespace XTrans.XferTableAdapters
{
public partial class FooTableAdapter
{
int? _timeout = null;
///<summary>
///Get or set the current timeout in seconds for Select statements.
///</summary>
public int CurrentCommandTimeout
{
get
{
int timeout = 0;
if (_timeout != null)
{
timeout = (int)_timeout;
}
else
{
for (int i = 0; i < this.CommandCollection.Length; i++)
if (this.CommandCollection[i] != null)
timeout = this.CommandCollection[i].CommandTimeout;
}
return timeout;
}
set
{
if (this.CommandCollection == null)
this.InitCommandCollection();
for (int i = 0; i < this.CommandCollection.Length; i++)
if (this.CommandCollection[i] != null)
{
this.CommandCollection[i].CommandTimeout = value;
_timeout = value;
}
}
}
}
}
If you go to [name of DataSet].Designer.cs which is a file added under the data set file in the solution and then search for :
private void InitCommandCollection();
This is a function that you should be able to set properties for functions that have been defined in a table adapter.
The first line in that function is
this._commandCollection = new global::System.Data.IDbCommand[<number of function defined in a table adapater>];
and then in the next line for each of those function, you can set
((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[<index>])).CommandTimeout = 0;
which 0 indicates no limitation and the function will not stop due to the time out and also it can be set to 10, 20, 30 or 1000 and so on
After scratching my head all day long I finally got the resolution for this. After designing your .xsd file all you need to do is go to your dataset.designer.cs page which is an auto generated page and change the code to provided below. It really works. Give it a try.
protected global::System.Data.SqlClient.SqlCommand[] CommandCollection
{
get
{
if ((this._commandCollection == null))
{
this.InitCommandCollection();
_commandCollection[0].CommandTimeout = 0;
}
_commandCollection[0].CommandTimeout = 0;
return this._commandCollection;
}
}

Categories