Software Development : A dizzy job...keeping abreast and being competitive is a 24X7 involvement
Jan 19, 2016
Using Fiddler to test Web API Rest Services and pass an array as parameter + Filtering
2. In the same tab, Change GET to POST and enter the address of your Web.api controller (“http://yoursite.com/api/yourControllerName”).
3. Again, under the same tab, In the Request headers Text Box Area (The heading 'Request Headers' may not be visible), enter a JSON content type. “Content-Type: application/json; charset=utf-8″ (w/o the braces). 4. Again, under the same tab, Put your JSON string array (Input param) in the Request Body. e.g., ["aaa","bbbbb","cccccccc"].
5. Click on "Execute". it will hit the controller and you can debug.
To Filter the huge number of network communications recorded in the Fiddler
1. Click on the "Filters" tab, Select "Use Filters"
2. In the 1st drop down under the Hosts Heading, Select "Show Only Intranet Hosts", in the second drop down, select "Show only the following Hosts"
3. In the following text box enter: Enter the local url for e.g. "http://localhost:31314/", here, I was hosting the service in IISExpress.
Dec 17, 2015
Fluent code in c sharp
In LINQ, the 'fluent' method syntax flows logically and intuitively, and allows them to be combined simply, because each method returns the appropriate type of object for the next. Can this fluent technique be extended as an API style to make it easier to develop C# team-based applications for enterprises?
Read about it here
A-Look-at-Fluent-APIs
Dec 10, 2015
Compile your asp.net mvc Razor views into a separate dll
Pre-compiling-razor-views
Precompile-mvc-views
Detect-errors-of-asp-net-mvc-views
Dec 4, 2015
Web Designing : screen-patterns
http://blogs.msdn.com/themes/blogs/generic/postlist.aspx?WeblogApp=infopath&PageIndex=3
Nov 18, 2015
Asynchronous Programming with Async and Await (MSDN) + Extra
https://code.msdn.microsoft.com/Async-Sample-Example-from-9b9f505c
http://www.abhisheksur.com/2010/10/c-50-asynchronous-made-easy.html
(Excerpted from http://www.abhisheksur.com/2010/10/c-50-asynchronous-made-easy.html)
What is await ?
According to Whitepaper published on the CTP, await keyword lets you to wait your program and lets the program to be declared as a continuation of all the existing awaits so that the compiler automatically waits for all other awaits to be finished until the program continues its execution.
In other words, say you have invoked
async TaskGetStringsFromUrlAsync(string url) { WebClient client = new WebClient(); return await client.DownloadStringTaskAsync(new Uri(url)); }
This involves the call to DownloadStringTaskAsync which is already implemented for WebClient. Now as you can see I have specified the await just before the call to Asyncrhonous method DownloadStringTaskAsync, it will keep the call on wait.
Even though if I say use :
async TaskGetStringsFromUrlAsync(string url) { WebClient client = new WebClient(); Task<string> modifieduri = client.DownloadStringTaskAsync(new Uri(url)); string result = await modifieduri; return await client.DownloadStringTaskAsync(new Uri(result)); }
It means the second Task depends on the first one. So in this case the First DownloadStringTaskAsync will be called. This call actually returns Task(Task for any other operation) which you can keep on wait until it is finished using await keyword. So when you execute, the first call will block until the result is fetched and then it will take the string result and call the next one.
Thus you can see how you can use await on Task variable to wait the object for completion without any implementation of custom callbacks, global objects etc.
What is async?
Now, how to implement the asynchronous method? Hmm, async keyword can be placed just before the function call to make the method asynchronous.
By specifying the async keyword against your method call, the compiler will automatically select your method to be asynchronous, which means it will move to the next line before returning the result in parallel until it finds an await. In the example I have provided theDownloadStringTaskAsync is actually an extension which specifies to be called with async.
Async method can return void, Task or Task based on what you need in your environment. But it is mostly preferable to return at least a Task object so that the caller can better handle the call.
For any async method, you should put await before fetching the result, otherwise you might end up with blank/null result. await works with async to stop the further execution before finishing the other operations in context.
C# 6.0: Language features and its internals Part 1
---------------------------------------------------------------------------------------
(excerpted from http://www.abhisheksur.com/2015/03/c-60-language-features-and-its.html)
The feature set which have been added / modified as part of C# 6.0 are:
1. Auto Property Initializer
2. Expression bodied Function
3. Static Class Uses
4. String Interpolation
5. Null Conditional operators
6. Exception filters
7. nameof operator
8. Dictionary initializers
9. await in try / finally.
10. Parameterless constructor for struct
------------------------------------------------------------------------------------
Feature 1 : Auto Property Initializer
Auto properties are not new to C#. It was there since C# 3.0. The auto properties does not require a backing field to be defined which was done automatically during compilation. So as a coder, you can get a ready-made property without writing much of code. As auto properties does not have backing field exposed, you cannot initialize the backing field during object initialization, rather you have to initialize explicitly in constructors.
public class AutoPropertyInitialier { public string FirstName { get; set; } public string LastName { get; set; } public string FullName { get; set; } public AutoPropertyInitialier() { this.FirstName = "Abhishek"; this.LastName = "Sur"; this.FullName = this.FirstName + " " + this.LastName; } }
With C# 6.0, the initialization of auto-implemented properties is damn easy. Take a look into the code below :
public class AutoPropertyInitializer { public string FirstName { get; set; } = "Abhishek"; public string LastName { get; } = "Sur"; //public string FullName { get; } = this.FirstName + this.LastName; public string FullName { get; } public AutoPropertyInitializer() { this.FullName = this.FirstName + " " + this.LastName; } }
Here the properties FirstName and LastName were initialized directly after the declaration. You can notice the LastName were intentionally made readonly by not mentioning the setter. The backing field produced for a readonly property is also a readonly variable.
The FullName though is initialized inside constructor as the object initialization works before the constructor call, and hence initialization cannot evaluate "this".
Feature 2 : Expression bodies functions
public class ExpressionBodiedFunction { public string WelcomeMsg(string name) => string.Format("Welcome {0}", name); public string HelloMsg => "Abhishek"; public void Print() => Console.WriteLine(this.HelloMsg); }
The second property is HelloMsg which is a property like method where the getter of the property HelloMsg will return the string "Abhishek". Remember, as property is also auto-implemented, the get keyword is also automatically evaluated by the compiler.
The last method "Print" is a void method and hence require a non-returning expression. The Console.WriteLine calls the property HelloMsg to print "Abhishek".
Now how does the compiler handles the lambda now without an explicit declaration of delegates ? Well, the answer is simple. The compiler re-writes the lambda into a full functional method body.
Feature 3 : Static class uses
The C# language teams identified the developers pain points very well, and implemented the Static class uses in the language. If you are using Static types it is always a nice to have feature in the language such that we can omit the repetitive static method call.
For instance, say I want to print a number of lines on screen, using Console.WriteLine. How about if we don't need to mention Console each line when we call WriteLine ? Static class uses does the same thing. Static class uses also recognize extension methods, hence if say a static class defines extension methods, if you add it, it will automatically recognize the extension methods as well.
using static System.Console; using static System.Linq.Enumerable; public class UseStatic { public void CallMe() { WriteLine("Hi"); var range = Range(10, 10); var check = range.Where(e => e > 13); // Static extension method can // only be called with fulll representation } }
In the above code the WriteLine is automatically detected as we added the head using static statement. The Range is also declared inside System.Linq.Enumerable which is automatically determined and Where is an extension function. The static uses automatically recognized the extension methods as well.
If you look at the internals of the static uses, the compiler rewrites the static type calls on every occurrences of its method call.
In the actual IL, you can see, the WriteLine is padded with its appropriate type Console and Range is also associated with Enumerable. The re-writing is done by the compiler.
Feature 4 : String Interpolation
String interpolation is another interesting feature introduced with recent version of C# 6.0. Interpolation is not new with strings. We can do string interpolation using string.Format before, but the problem is the code looks really ugly when using interpolation constructs.
For instance,
string myString = "FullName :" + p.First + " " + p.Last; string myString = string.Format("FullName : {0} {1}", p.First, p.Last);
C# 6.0 comes with a new technique where the string interpolation can take place in between the strings, or rather than putting numeric placeholders, you can use the actual values.
string myString = $"FullName : {p.First, 5} {p.Last, 20}"; Console.WriteLine(myString); string my2ndString = $"FullName from EBF = {this.EBF.FullName}"; Console.WriteLine(my2ndString);
Here Feature 4 :the string need to be started with a $ sign which indicates that the new kind of string interpolation to occur. The {p.First, 5} will be replaced with the value of p.First aligned to 5 characters.
Now what does the compiler do when these kind of interpolation is encountered. Well, you might be surprised to see, that the string is actually replaced by a call of String.Format during compilation.
Feature 5 : Null conditional operators
Getting into NullReferenceException or "Object reference not set to instance of an object" is one of the most common exception that every developer must see while working with the langauge. It has been a common problem where developers need to give extra stress to check the null value before calling any member functions. Null for compiler is unknown, and hence if you call a method on null, it will point nowhere and hence throws NullReferenceException and exists the stack.
To handle nulls Microsoft had introduced few language constructs already like Null coalesce operator (??) or Conditional operators. But with the new feature introduced in C# 6.0, the language team has introduced another operator which checks for null.
Null Conditional operator is a new construct that gives away a shortcut to condition the null check before calling its members.
string zipcode = (address == null? null : address.zipcode); string zipcode = (person == null? null : (person.address == null ? null : person.address.zipcode))
Here in the above two lines you can see how the complexity rises when there are multiple number of null checking on an expression. In the first statement the address is checked with null and when it has address, it will only then evaluate the zipcode. On the second statement, the person object is checked with null, then its address and then finally the zipcode is evaluated.
With null conditional operator the code would look like :
string zipcode = address?.zipcode; string zipcode = person?.address?.zipcode;
Here the code is reduced greatly even though the actual expression logic remains the same. The ? mark is used for null conditioning. Null conditional operators does not exists as well, it is the same representation as that of the previous conditional operators. If you try to look into reflector, you will see it like :
You can see the null conditional operators are replaced by the compiler with normal conditional statements.
Feature 6 : Exception Filters
Now after so many syntactic sugar introduced with latest version of C#, this is the only new feature that directly relates to IL (Intermediate Language). From the very inception, the exception filters were there in CLR but was not exposed to the C# language. With C# 6.0, the exception filters finally came into existence and finally as a C# developer you can make use of it.
In C# the exception block contains try/catch/finally with multiple catch blocks supported. Based on type of the exception that has been encountered during runtime, the runtime chooses the appropriate catch block to execute. Exception filters allows you to filter out the catch blocks to ensure which catch block can handle the exception. With exception filters in place, there could be multiple catch blocks with same type where the type determines which filter it will call first.
Let us take a look at the code :
public class ExceptionFilters { public static bool LogException(Exception ex) { //Log return false; } public static bool LogAgainException(Exception ex) { //Log return true; } public void CallMe() { try { throw new ArgumentException("Exception"); } catch (Exception ex) when (LogException(ex)) { //Keep exception stack intact } catch(Exception ex) when (LogAgainException(ex)) { // Calling the catch } } }
Here the ArgumentException is thrown when CallMe is invoked. The Exception filters are specified using when keyword just like in VB.NET. So the execution is like, it will call LogException method, executes the code and see whether the return statement is true or false. If it is true, it executes the catch block and exit, or otherwise it move and call LogAgainException method.
The exception filter expects a boolean value, hence the call to LogException should be a method returning bool or otherwise we need a comparison operator to always evaluate the when statement to boolean. Exception filters allows the developer to run arbitary code between the exception and the catch block execution without interfering the original stack trace of the exception object.
I have already told you that exception filters is a CLR concept. The IL is laid out as :
.try --- to --- filter --- handler --- to ---
This tells the compiler to execute try block from line no --- to line ----. It will then call filter line and then call the handler which executes some bunch of lines. Cool ? Yes.
One small addition that I would want to add, if an exception filter encounters an exception and is left unhandled, the compiler handles it for you and automatically skip the exception block and moves to the next catch block. For instance if LogException in the code above throws an exception, it will call LogAgainException without modifying the Stack for ex.
Feature 7 : nameof Operator
nameof is a new addition to operator list supported by C#. This new operator is nothing but a compiler trick, where the compiler determines the name of a Property, Function or an Extension method and writes it directly in compiled output. For instance,
string name1 = nameof(this.MyProp); // evaluates MyProp string name2 = nameof(DateTime.Now);//evaluates Now string name3 = nameof(Console.WriteLine); //evaluates WriteLine string name4 = nameof(new List<string>().FirstOrDefault); // Evaluates FirstOrDefault
string name5 = nameof(name4);//Evaluates name4
The nameof operator works on any type where the type has a name. In case you specify a variable, the nameof operator will evaluate to the name of the variable.Feature 8 : Dictionary initializers
Dictionary is one of the common array object which used often to send data between objects. Unlike arrays, Dictionaries form an array of KeyValuePair. In modern days, Dictionary is used interchangeably with arrays because of its flexibility of defining key value set.
var list = new List<string>(); list.Add("Abhishek"); list.Add("Abhijit"); //Access var first = list[0]; var second = list[1];
Here you can see a list is used to store string data, where index giving you the reference to individual objects. If I write the same with dictionary, it will look like :
var dict = new Dictionary<int,string>(); dict.Add(0, "Abhishek"); dict.Add(1, "Abhijit"); //Access var first = dict[0]; var second = dict[1];
Even though the basics remain the same, the developers are increasingly inclined to use the later as it gives a flexibility to assign any index. You can define "Abhishek" to 10 and "Abhijit" to 20 without the limitation of fixed incremental index usage of dictionary.
As more and more people are going to Dictionary, language team thought about giving easier constructs to define Dictionary. Even though we can go without it, but it is a nice to have feature. In C# 6.0, you can define dictionary using the following syntax :
var dict = new Dictionary<int,string> { [10] = "Abhishek", [20] = "Abhijit" }; //Access var first = dict[10]; var second = dict[20];
Or even if the key is declared as string, you can also use like:
var dict = new Dictionary<string,string> { ["first"] = "Abhishek", ["second"] = "Abhijit" }; //Access var first = dict["first"]; var second = dict["second"];
This way it is very easier to declare and use dictionaries. The last two syntaxes were introduced in C# 6.0.
Now if you think of the actual implementation, there is nothing as such. If you try to sneak peek on the compiled code, you will be seeing the same code with object being initialized inside the constructor.
Here even though the new construct is used, the dictionary object is actually initialized in constructor itself. The code is re-written by the compiler.
Feature 9: Await in catch and finally
If you are not using async / await stuffs too often you might have already overlooked that you cannot specify await in catch or finally block before the latest version of C#. Microsoft has initially thought that it wont be possible to allow awaits in catch/finally because the compiler creates a state machine which slices each and every await statements into a sequence of calls which can pause and resume the function upon request. But as try/catch/finally are handled by CLR, allowing such thing will indicate every errors in the state machine is properly handled and also each of try/catch/finally would need their individual state machines each.
Based on the complexity, microsoft haven't provided the feature in previous version, but as everything is handled by the compiler itself, it is a very important feature to have as a programmers perspective hence in latest version of C# 6.0, the feature have been revised and await in catch/finally is allowed.
public async Task<string> DownloadUrl(string url) { WebClient client = new WebClient(); client.BaseAddress = "www.abhisheksur.com"; try { return await client.DownloadStringTaskAsync(url); } catch { return await client.DownloadStringTaskAsync("mvp"); } finally { //Await is also allowed. } }
Hence you can successfully compile the code above where the await works during the catch execution.
If you try looking at the code in reflector it will look very ugly with so many of StateMachine declarations and so many of goto statements to properly navigate to lines inside the state machine on failure. It would be nice if you can look into it personally, but if there is any problem understanding the implementation, feel free to ask me in discussions.
But as a benefit, you get this feature ready.
Feature 10: Parameterless constructor for struct
If you are unaware, there was no parameterless constructors in struct. This is because of the fact that ValueTypes has a unique behavior where it will be automatically assigned a default memory when declared.
For instance,
int x;
Here int is a struct (System.Int32) and the value of x would be automatically 0. You can even declare array of a struct. For instance,
struct MyStruct { public int Property1{get;set;} public string Property2 {get; set;} } MyStruct[] array = new MyStruct[10];
Now the Struct MyStruct will automatically get the default(MyStruct) in the array even though its not explicitly constructed. If you want to know more why struct does not support default constructor, feel free to read the article I posted .
In C# 6.0 the parameterless constructor is allowed. This is also a trick made by the compiler. It actually replaces the default constructor with the parameterless constructor passed in when the new operator is used to construct the object.
So if you say,
MyStruct s = new MyStruct();
The .NET will call the parameterless constructor for you.
Apr 14, 2015
How to hard reset Visual Studio instance
- Enjoy your brand new Visual Studio instance.
Use {version}=11.0 for Visual Studio 2012
Use {version}=12.0 for Visual Studio 2013
Apr 4, 2015
Connect to a SQL Server DB which is on a client Network while you are using your office PC
Try this: Use RUNAS to set your Windows Auth domain for database connections
runas /user:domain\user "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\ssmsee.exe"
runas /user:domain\user "C:\WINDOWS\system32\mmc.exe /s \'C:\Program Files\Microsoft SQL Server\80\Tools\BINN\SQL Server Enterprise Manager.MSC\'"
runas /user:domain\user isqlw
Example:
runas /netonly /user:cricket\mdatta " C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\ssms.exe"
runas /netonly /user:cricket\mdatta isqlw
May 27, 2014
Mar 3, 2014
MS Outlook --> Power point Presentation in attachment--> quick preview --> Mouse cursor dissappears
Oracle.DataAccess.dll version mismatch...
I had compiled a local asp.net mvc project pointed to my installed version of the Oracle.ataaccess.dll (from the GAC). Instead of a complete project deployment, I was supposed to just replace the main project dll in the server.
Upon deployment, I found that the version of the Oracle.Dataaccess.dll was not the same and i was getting a "Version Mismatch error", whenever there was a call from the site to the Oracle DB. The Ora Client version in my dev box was 12.1.1.0.
To add to it, the environments of the Dev and the Web server were also different. My local dev box was a 32bit Win 7 whereas the webserver was a 64bit Win Server 2008 R2.
So the first challenge was to know what is the installed version of the Oraclient in Server.
I could not locate the Oracle Client in the usual place on the server, i.e., C:/
1. So I opened the Environment Variables of the server and from the Path Variable found the path to the Oraclient.
From there I got the Oraclient version.
2. I opened the GAC of the machine to confirm the version
3. I downloaded the exsiting dll of the mvc project and dissembled it (using ILSpy) to see the referenced Oracle version.
I found that the used version on the server was 11.2.3.0
----------------------
Now that I know of the 2 versions, the next challenge was to fix the mismatch of the versions.
The first thing which came to my mind was to uninstall the local version, download and install the one on the server, recompile and the replace the dll.
But that was a cumbersome process, and I couldn't find the exact oraclient version on the net too.
So, I investigated aa little more... From the experience of a previous project, i knew that in the web.config we can instrument the assembly which we want to be loaded.
Then I found this website with the steps: it was not an exact same scenario, but quite close.
(http://tiredblogger.wordpress.com/2008/11/06/getting-oracledataaccess-working-on-x64/)
taking a cue from the website I added the following section to my web.config
<dependentAssembly>
<assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342"/>
<bindingRedirect oldVersion="0.0.0.0-4.121.1.0" newVersion="4.112.3.0"/>
</dependentAssembly>
ohh and BTW, I got the public key token of the installed oraclient version from the dissembled dll.
Feb 11, 2014
What NOT to do in ASP.NET
Excerpted from Scott Hanselman's blog.
A must read for all web programmers...
- Standards Compliance
- Control Adapters - Control adapters were a good idea in .NET 2, but it's best to use solid adaptive CSS and HTML techniques today.
- Style Properties on Controls - Set CSS classes yourself, don't use inline styles.
- Page and Control Callbacks - Page Callbacks pre-date standard AJAX techniques, so today, stick with SignalR, Web API, and JavaScript.
- Browser Capability Detection - Check for features, not for browsers whenever possible.
- Security
- Request Validation - While Request Validation is useful, it's not focused and it doesn't know exactly what you app is doing. Be smart and validate inputs with the full knowledge of what your app is trying to accomplish. Don't trust user input.
- Cookieless Forms Authentication and Session - Don't pass anything auth related in the query string. Cookieless auth will never be secure. Don't do it.
- EnableViewStateMac - This should never be false. Ever.
- Medium Trust - Medium trust isn't a security boundary you should count on. Put apps in separate app pools.
- Don't disable security patches with appSettings. - UrlPathEncode - This doesn't do what you think it does. Use UrlEncode. This method was very specific, poorly named, and is now totally obsolete.
- Reliability and Performance
- PreSendRequestHeaders and PreSendRequestContext - Leave these alone making managed modules. These can be used with native modules, but not IHttpModules.
- Asynchronous Page Events with Web Forms - Use Page.RegisterAsyncTask instead.
- Fire-and-Forget Work - Avoid using ThreadPool.QueueUserWorkItem as your app pool could disappear at any time. Move this work outside or use WebBackgrounder if you must.
- Request Entity Body - Stay out of Request.Form and Request.InputStream before your handler's execute event. It may not be ready to go.
- Response.Redirect and Response.End - Be conscious of Thread.Aborts that will happen when you redirect.
- EnableViewState and ViewStateMode - There's no need to hate on ViewState. Turn it off everywhere, then turn it on only for the individual controls that need it.
- SqlMembershipProvider - Consider using ASP.NET User Providers, or better yet, the new ASP.NET Identity system.
- Long Running Requests (>110 seconds) - ASP.NET isn't meant to handle long running requests that are a minute (or two) long. Use WebSockets or SignalR for connected clients, and use asynchronous I/O operations.
Sep 5, 2013
Sep 4, 2013
2. Using Facebook to Authenticate your ASP.NET MVC WebSite
Aug 30, 2013
Silverlight + WCF : Polling Duplex Examples
2. http://www.dotnetcurry.com/ShowArticle.aspx?ID=726
4. http://go4answers.webhost4life.com/Example/wcf-polling-duplex-binding-non-171992.aspx
Great Tech Blogs
| Sl | Blog | Url | Description |
| 1 | Ido Flatows Blog | http://feeds.feedburner.com/IdoFlatowsBlog | Area of expertise: WCF, Azure, IIS, IIS Perf (http://feedproxy.google.com/~r/IdoFlatowsBlog/~3/qiMlWjxYP1I/fixing-iis-advanced-logging-performance-counters-errors.aspx) |
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | |||
| 6 | |||
| 7 | |||
| 8 | |||
| 9 | |||
| 10 |
Jul 3, 2013
A Visual Explanation of SQL Joins
Sql Joins and Venn Diagrams..
A very interesting read
How to loop in Sql Server
Scenario: We have a Table : TableA
Structure of TableA:
Id Name
-- ---------------------------
1 Pirate
2 Monkey
3 Ninja
4 Spaghetti
-------------------------------
Requirement: Iterate through the Names (“Name” column) of TableA
Solution:
We all know that the most convenient, easy and widely used solution is by using a Cursor.
DECLARE cursor1 CURSOR
FOR SELECT Name FROM TableA
OPEN cursor1
FETCH NEXT FROM cursor1
This works, but we should be aware of the disadvantages of using a Cursor…
Cursor implementation in application, helps data manipulation easy and even they are very effective but due to some major disadvantage of Cursor normally they are not preferred.
Disadvantages of cursors
- Uses more resources because Each time you fetch a row from the cursor, it results in a network roundtrip
- There are restrictions on the SELECT statements that can be used.
- Because of the round trips, performance and speed is slow.
- As we know cursor doing round trip it will make network line busy and also make time consuming methods. First of all select queries generate output and after that cursor goes one by one so round trip happen.
- Another disadvantage of cursor are there are too costly because they require lot of resources and temporary storage so network is quite busy.
Apart from these I would like to point out some great advantages of cursor if the entire result set must be transferred to the client for processing and display.
- Client-side memory : For large results, holding the entire result set on the client can lead to demanding memory requirements on client side system.
- Response time : Cursors can provide the first few rows before the whole result set is assembled. If you do not use cursors, the entire result set must be delivered before any rows are displayed by your application.
- Concurrency control :It's a general problem with current applications, If you make updates to your data and do not using cursors in your application, you must send separate SQL statements to the database server to apply the changes. This raises the possibility of concurrency problems if the result set has changed since it was queried by the client. In turn, this raises the possibility of lost updates.But Cursors act as pointers to the underlying data, and so impose proper concurrency constraints on any changes you make.
Some Alternatives to using a Cursor:
- Use WHILE LOOPS
- Use temp tables
- Use derived tables
- Use correlated sub-queries
- Use the CASE statement
- Perform multiple queries
It has been generally observed that looping without using a cursor is faster than looping using a cursor.
Some solutions:
1. Add the recordset to a new Temp Table and also introduce a new column to the temp table.
*****************************************************
set rowcount 0
select NULL mykey, * into #mytemp from TableA
set rowcount 1
update #mytemp set mykey = 1
while @@rowcount > 0
begin
set rowcount 0
select * from #mytemp where mykey = 1
delete #mytemp where mykey = 1
set rowcount 1
update #mytemp set mykey = 1
end
set rowcount 0
*****************************************************************
2. The following solution assumes that there is a unique indexed int column named id.
declare @id char( 11 )
select @id = min( id ) from TableA
while @id is not null
begin
select * from TableA where id = @id
select @id = min( id ) from TableA where id > @id
end
****************************************************************
3. Here to the temp table we are adding a new column (RowID ) which is a identity column
DECLARE @RowsToProcess int
DECLARE @CurrentRow int
DECLARE @SelectCol1 int
DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), Name varchar(50))
INSERT into @table1 (Name ) SELECT Name FROM tableA
SET @RowsToProcess=@@ROWCOUNT
SET @CurrentRow=0
WHILE @CurrentRow<@RowsToProcess
BEGIN
SET @CurrentRow=@CurrentRow+1
SELECT
@SelectCol1=Name
FROM @table1
WHERE RowID=@CurrentRow
--do your thing here--
END
******************************************************************
4.
DECLARE @table1 TABLE (
idx int identity(1,1),
col1 int )
DECLARE @counter int
SET @counter = 1
WHILE(@counter < SELECT MAX(idx) FROM @table1)
BEGIN
DECLARE @colVar INT
SELECT @colVar = col1 FROM @table1 WHERE idx = @counter
-- Do your work here
SET @counter = @counter + 1
END
Believe it or not, this is actually more efficient and performant than using a cursor.
*********************************************************************
5.
DECLARE
@LoopId int
,@MyData varchar(100)
DECLARE @CheckThese TABLE
(
LoopId int not null identity(1,1)
,MyData varchar(100) not null
)
INSERT @CheckThese (YourData)
select MyData from MyTable
order by DoesItMatter
SET @LoopId = @@rowcount
WHILE @LoopId > 0
BEGIN
SELECT @MyData = MyData
from @CheckThese
where LoopId = @LoopId
-- Do whatever
SET @LoopId = @LoopId - 1
END
*********************************************************************
6.
*********************************************************************
While fetching we should always remember that SQL Server Queries are SET Based operations and work best in circumstances dealing with SET Based operations.
You can loop through the table variable or you can cursor through it. This is what we usually call a RBAR - pronounced Reebar and means Row-By-Agonizing-Row.
So, we should always strive to find a SET-BASED answer and move away from RBARs as much as possible.
Set based queries are (usually) faster because:
- They have more information for the query optimizer to optimize
- They can batch reads from disk
- There's less logging involved for rollbacks, transaction logs, etc.
- Less locks are taken, which decreases overhead
- Set based logic is the focus of RDBMSs, so they've been heavily optimized for it (often, at the expense of procedural performance)
Jul 2, 2013
Popular Javascript Frameworks
Knockout.js
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintain-ably.
Angular.js
AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running what are known as single-page applications. Its goal is to augment browser-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier. The library reads in HTML that contains additional custom tag attributes; it then obeys the directives in those custom attributes, and binds input or output parts of the page to a model represented by standard JavaScript variables. The values of those JavaScript variables can be manually set, or retrieved from static or dynamic JSON resources.
http://angularjs.org/
Backbone.js
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
http://backbonejs.org
Node.js
Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
http://nodejs.org/
Modernizr
Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation web technologies, i.e. features that stem from the HTML5 and CSS3 specifications. Many of these features are already implemented in at least one major browser (most of them in two or more), and what Modernizr does is, very simply, tell you whether the current browser has this feature natively implemented or not.
http://modernizr.com
Require.js
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
http://requirejs.org
Less
LESS extends CSS with dynamic behaviour such as variables, mixins, operations and functions.LESS runs on both the server-side (with Node.js and Rhino) or client-side (modern browsers only).
http://lesscss.org/
Sass
Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.
http://sass-lang.com
Source: http://www.codeproject.com/Articles/596800/JavaScript-Frameworks-and-Resources
Jan 30, 2013
Dynamic Dictionaries with C# 4.0
Have you ever been working with the Dictionary
var dictionary = new Dictionary { { "hello", "world!" } };
...
var something = dictionary.hello;
It'd be sweet, but it's not possible. The dictionary is just a bucket and there isn't a way it can know at compile type about the objects which are within it. Damn, so you just have to go via the indexer of the dictionary.
But really, using dot-notation could be really cool!
Well with the .NET 4.0 framework we now have a built in DLR so can we use the dynamic features of the C# 4 to this?
Introducing the DynamicObject
Well the answer is yes, yes you can do this, and it's really bloody easy, in fact you can do it in about 10 lines of code (if you leave out error checking and don't count curly braces :P).
First off you need to have a look at the DynamicObject which is in System.Runtime. There's a lot of different things you can do with the DynamicObject class, and things which you can change. For this we are going to work with TryGetMember, with this we just need to override the base implementation so we can add our own dot-notation handler!
So lets start with a class:
using System;
using System.Collections.Generic;
using System.Dynamic;
namespace AaronPowell.Dynamics.Collections
{
public class DynamicDictionary : DynamicObject
{
private IDictionary dictionary;
public DynamicDictionary(IDictionary dictionary)
{
this.dictionary = dictionary;
}
}
}
Essentially this is just going to be a wrapper for our dynamic implementation of a dictionary. So we're actually making a class which has a private property which takes a dictionary instance into the constructor.
Now we've got our object we need do some work to get it handle our dot-notation interaction. First we'll override the base implementation:
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var key = binder.Name;
if (dictionary.ContainsKey(key))
{
result = dictionary[key];
return true;
}
throw new KeyNotFoundException(string.Format("Key \"{0}\" was not found in the given dictionary", key));
}
And you know what, we're actually done! Now all you have to do:
var dictionary = new Dictionary {{ "hello", "world!" }};
dynamic dynamicDictionary = new DyanmicDictionary(dictionary);
Console.WriteLine(dynamicDictionary.hello); //prints 'world'
I'm going to be releasing the source for this shortly (well, an improved version), along with a few other nifty uses for dynamic. So keep watching this space for that ;).
----------------------------------------------------------
By overriding the TryGetMember and TrySetMember method you can dynamically add and remove properties.
dynamic person = new DynamicClass; person.Name = “John Smith”; person.Phone = “32345690″;
By overriding the TrySetIndex and TryGetIndex you can access properties you don’t know about at compile time. dynamic person = new DynamicClass; person["Name"] = “John Smith”;
and then both are interchangable
public class DynamicDictionary : DynamicObject
{
private Dictionary _dictionary = new Dictionary();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _dictionary.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_dictionary[binder.Name] = value;
return true;
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
if (dictionary.ContainsKey((string)indexes[0]))
_dictionary[(string)indexes[0]] = value;
else
_dictionary.Add((string)indexes[0], value);
return true;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
return _dictionary.TryGetValue((string)indexes[0], out result);
}
}
}
Umbraco
While we were working on some sexy features for Umbraco 5 over the CodeGarden 10 retreat we kept saying that we should look at using as many of the cool new .NET framework features which we can possibly get away with. To this extent we kept saying we need to work out how to implement the dynamic keyword in some way.
Well that's where the idea for the above code came from, in fact we've got a similar piece of code which will be usable within the framework of Umbraco 5 and entity design. But the full info on that will belong to another post ;).
Released!
I've rolled the above code (with some improvements mind you) into a new project that I've been working on for making working with dynamics in .NET a whole lot easier. You can check out my Dynamics Library and get dynamacising.







