Insert rows from one table to another

WITH rates(Code, Rate, BaseCode, LastUpdate, [Auto], Source) 
 AS (SELECT crc.Code, crc.Rate, crc.BaseCode, crc.LastUpdate, crc.[Auto], crc.Source
  FROM CurrencyRateCurrent crc
  WHERE crc.AccountId = 7
  )

INSERT INTO [CurrencyRateCurrent] (Code, Rate, BaseCode, LastUpdate, [Auto], Source,AccountId)
SELECT Code, Rate, NULL, LastUpdate, [Auto], Source, 20 FROM rates

Serializare/ Deserializare

 

public static string SerObjXML(object rspJ, Type type)
         {
             string serObj = null;

             MemoryStream ms = new MemoryStream();
             XmlSerializer bf1 = new XmlSerializer(type);
             bf1.Serialize(ms, rspJ);
             ms.Position = 0;
             StreamReader sr = new StreamReader(ms);
             serObj = sr.ReadToEnd();

             return serObj;
         }

  public static object DeSerObjXML(string xml, Type type)
         {
             XmlSerializer xs = new XmlSerializer(type);
             MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
             XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
             return xs.Deserialize(memoryStream);
         }

string returnReqXMLss = Common.SerObjXML(sRspData, typeof(JacobClasess.Search.SearchResponseData));

Fastest Bulk Inserts

Fastest universal way to insert data using standard ADO.NET constructs Now that the slow stuff is out of the way, lets talk about some hardcore bulk loading. Aside from SqlBulkCopy and specialized constructs involving ISAM or custom bulk insert classes from other providers, there is simply no beating the raw power of ExecuteNonQuery() on a parameterized INSERT statement.


 
internal static void FastInsertMany(DbConnection cnn)
{

  using (DbTransaction dbTrans = cnn.BeginTransaction())

  {

    using (DbCommand cmd = cnn.CreateCommand())

    {

      cmd.CommandText = "INSERT INTO TestCase(MyValue) VALUES(?)";

      DbParameter Field1 = cmd.CreateParameter();

      cmd.Parameters.Add(Field1);

      for (int n = 0; n < 100000; n++)

      {

        Field1.Value = n + 100000;

        cmd.ExecuteNonQuery();

      }

    }

    dbTrans.Commit();

  }

}

Simple, elegant, clean.  100,000 inserts on my machine in 1.4 seconds.  Yes, that’s 10 times more inserts than the DataAdapter/DbCommandBuilder/DataTable method, and at very nearly the same speed as example 1!

Do not, under any circumstances, bulk insert data by building your own command text over and over and over again.  That is the surest way to drag performance into the dirt.  Build your CommandText one time, build your parameters one time, and set their values over and over and over instead.  SQLite runs much faster, SQL Server runs much faster, and every database known to mankind will run much faster with a prepared, parameterized insert statement.

source: Fastest Bulk Inserts

Dynamically executing code in .Net

Dynamic code execution is a powerful feature that allows applications to be extended with code that is not compiled into the application. Users can customize applications and developers can dynamically update code easily. In this article, Rick takes a look what it takes to execute code dynamically with the .Net framework and introduces a class that simplifies the tasks by wrapping the details of the process in an easy to use interface that only requires a few lines of code.

Assemblies and Namespaces

In order for code to compile properly it needs both a physical reference to an assembly and any namespace references in the source code. Both are required for the compiler to be able to properly identify and validate your types in the compiled code. You need to provide physical assemblies via the CompilerParameters.ReferencedAssemblies propety. It points to a physical DLL or EXE that contains the types you want to include in your code. You also have to add the appropriate namespace imports to your source code which means using (CSharp) or import (VB) commands for each namespace used. Remember that you may have more than one namespace you need to include for a single physical assembly. This can become cumbersome if you want build generic code as the namespace directives tend to be placed at the top of the document. The wwScripting class handles this with an AddAssembly and AddNamespace methods that handle adding the appropriate assemblies and delays creating of the assembly source code until the final compilation.

What’s an Application Domain?

With application domains .Net provides a hosting container inside of a running process that isolates code and data into separate sub applications or domains. In simplistic terms you can think of an Application Domain as a Process within a process that provides the ability to isolate different sets of code. Code and data available in one application domain within a single process is not directly accessible from another application domain. You can however access it through special code designed to instantiate and access types in other domains.

Application domains are useful for providing specific context to an application component. They are also necessary, as described in this article, if you need to unload assemblies at any point. Since an assembly loaded into an AppDomain can never be unloaded from within the domain the only way to release them is to unload the entire domain.

Accessing Code and Data in a different domain requires the use the .Net Remoting framework which provides mechanisms using proxies and stubs that are very similar to the way DCOM operates. These mechanisms allow access to AppDomains in the same process, in a different process and across machine and network boundaries.

source: Dynamically executing code in .Net

An Introduction to PageMethods

PageMethods offer a simple way to asynchronously communicate with a server using Microsoft’s ASP.Net AJAX technologies.  Unlike Update Panels which utilize the full page life cycle to synchronously update a section of the page based on the panel’s triggers, PageMethods handles the transmissions manually through JavaScript.  Since everything is manual, PageMethods take a small amount of additional time to develop; however, provides an additional level of efficiency that cannot be found in UpdatePanels.

In order to begin utilizing PageMethods in your ASP.Net AJAX enabled webpage, you need to do 3 things:

  • Set the ScriptManager’s “EnablePageMethods” property to “true”.
  • Write Public Static WebMethods in the Code Behind file of the web page that will return the information required.
  • Write JavaScript that calls the PageMethods and reacts to the return results (information or errors).
Setting up the Script Manager

Setting up the ScriptManager to handle PageMethods is fairly straightforward; however, there’s one thing that you’ll need to be aware of. The “EnablePageMethods” property is only found on the ScriptManager control and not the ScriptManagerProxy control. This means that if you have a Master Page with a ScriptManager control in it used by the Content Page that will contain the PageMethods, you must set the Master Page’s ScriptManger control to include the property. Doing such enables all pages that use that master page to be able to use PageMethods. I haven’t investigated to see the impact this has on pages that do not utilize PageMethods.

With that out of the way, in order to enable page methods on a page, simply go to your ScriptManager control that’s associated with the page and set the “EnablePageMethods” property to “True”. This is “False” by default, but once you set it to “True” you’re all set.

Writing the Server Code

Now that we can write PageMethods, we need to flip to our code behind files (or our <script runat=server> sections) to begin. Below are the steps that I traditionally follow when creating PageMethods:

  1. Create a new method/function that returns String or value type (Integers, Doubles, Dates, etc.).
  2. Mark the new method as Public Static (or Shared for the VB coders out there)
  3. Import the System.Web.Services namespace
  4. Add the [WebMethod()] (or <WebMethod()>) Attribute to the Function

In a nutshell, I write the method first. This allows me to get the logic in place just in case I need to modify the implementation when I’m in the middle of writing this code. Next, I ensure the proper scope and modifiers are setup on the method, and finally, mark the method as a WebMethod like I would with a web service.

[WebMethod()] 
public static string MyPageMethod(string someParam) 
{ 
return "Hello, PageMethods!"; 
}

When the page loads, the ScriptManager will examine the page’s definition for any public static webmethods. It will then generate JavaScript code that is used to call these methods and append it into the ASP.Net AJAX’s PageMethods object. This interaction allows our new method to be called from JavaScript by referencing in JavaScript the method of the same name of the PageMethods object ( PageMethods.MyPageMethod(…) in this case – more on this below).

Making the calls with JavaScript

So far we have enabled PageMethods in our ScriptManager and have made some static web methods in our code that the ScriptManager will create JavaScript from. Now, we need to write our own JavaScript code to call these PageMethods so that we can retrieve the information they provide.

In order to create the JavaScript code to call the PageMethods, you simply have to make have 3 things:

  1. The script that calls the PageMethod itself
  2. A function to call on each successful PageMethod call
  3. A function to call when ever there was an error in the PageMethod call.

The code to call the PageMethod is very simple.

function callerMethod() { 
    PageMethods.MyPageMethod(PARAM1, 
                             PARAM2, 
                             PARAMn, 
                             callerMethod_Success, 
                             callerMethod_Failure); 
} 

Let’s pick this apart now. What we have above is a simple JavaScript function called “callerMethod”. Inside of this function, we do a simple call to our method’s JavaScript counterpart that got attached to the PageMethods JavaScript object that’s included by the ScriptManager. Next, we pass any parameters required (signified by the “PARAM1”, “PARAM2”, and “PARAMn” in this case) followed by a pointer/name of the method to call on a successful transmission and the same for the failed transmission.

One optional parameter that I’ve purposefully excluded can appear at the very end is designated for the current UserContext. In a later posting, I will provide more information revolving around this parameter and how to use it to provide more powerful communication models in the code. For right now, we will exclude the parameter because we can.

Now that we’ve created the call, we need to create the functions that’ll be called when the transmission succeeds or fails.

function callMethod_Success(results, userContext, methodName) { 
    alert(results); 
}

function callMethod_Failure(errors, userContext, methodName) {
    alert(errors.get_Message()); 
}

Again, these are very simple methods that do nothing other than alerting the user of the resulting value on success or the error messsage on failure. The names of the methods are completely up to you naturally; however, whatever you name the methods, each require 3 parameters.

The first parameter of is for the returned value or error that the call to the PageMethod created. On success, you can immediately begin using the results as if they were a normal value passed into any regular function (since it’s either a String or Number JavaScript type). On failure, the PageMethod and ScriptManage return an object with information about the error. The get_Message() method of the error object will return the error message that was thrown during the transmission. Once you have the resulting value (success or failure), you can then write JavaScript logic to do whatever you want with it.

The second parameter is the userContext. Like previously stated, this will be covered in a future posting. For now, just remember that you can send the userContext to the PageMethod and read the resulting context on the returning trip.

The last parameter of the success and failure methods is the methodName. This parameter provides a simple string that represents the PageMethod name that was called and caused the success or failure function to be triggered. This is a great addition to the returning functions since it allows you to reuse success and/or failure functions across different PageMethods and produce custom logic based on which PageMethod was called. While I can see some merit in having a single success and a single failure (or even 1 function that does both), I wouldnt’ want to maintain the if statements that would spawn from such logic.

Summary

While the example code here isn’t too useful (like most Hello, World projects), it hopefully will get you started on using PageMethods. In future postings, I’ll provide some addition information and techniques that you can use in order to utilize PageMethods by using the UserContext object, identifying more in depth the data types that can and cannot be passed, and also object serialization through JSON. In addition to these items, I’ll also be keeping an eye out on any items that may be not quite so obvious when you’re work with PageMethods. Down the road a bit, I’ll do a very similar post to this about using local WebServices instead of PageMethods and why.

source: http://randomactsofcoding.blogspot.com/2007/10/introduction-to-pagemethods.html

Design Patterns

Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.

The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Here you will find information on these important patterns.

To give you a head start, the C# source code is provided in 2 forms: ‘structural’ and ‘real-world’. Structural code uses type names as defined in the pattern definition and UML diagrams. Real-world code provides real-world programming situations where you may use these patterns.

A third form, ‘.NET optimized’ demonstrates design patterns that exploit built-in .NET 4.0 features, such as, generics, attributes, delegates, object and collection initializers, automatic properties, and reflection. These and much more are available in our Design Pattern Framework 4.0TM. See our Singleton page for a .NET 4.0 Optimized code sample.


source: http://dofactory.com/Patterns/Patterns.aspx

SubSonic

SubSonic is A Super High-fidelity Batman Utility Belt that works up your Data Access (using Linq in 3.0), throws in some much-needed utility functions, and generally speeds along your dev cycle.

Our Focus is that you have better things to do with your time than worry about Data Access. It’s a problem – we understand. But we’re here to help with the addiction.

New to SubSonic? It’s easy to get started. Learn more about what SubSonic can do for you, or read our starup tutorial on using SubSonic in your project. If you’re a person who doesn’t like frameworks – we have something just for you.

website: http://www.subsonicproject.com/

Shove It, FizzBuzz: How To Find and Land a .NET Development Job

The kit includes a 200+ page eBook (PDF) that teaches you how to find and land the software development (C#, ASP.NET, VB.NET) job you want (and will make you a better developer in the process).

The book also contains tips on improving your overall developer marketability, 110+ technical questions (with answers), plus general interview questions, puzzle questions, and lots more. You will feel like a senior developer after reading this book.

The kit includes software that simulates an actual interview and can help boost your confidence during the real thing. You could also just use the software to keep yourself on top of the latest technologies. (Over 150 questions!)

The kit includes a customizable resume template (in Word format) that has proven to be effective at getting numerous people jobs.

web site: http://shoveitfizzbuzz.com/