Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Cache missing issue when concurrent requests are hitting

2022-05-04

 In application where there are concurrent requests are hitting, there is a high chance that your cache seems not working and most of the requests are hitting into DB for fetching the value and your cache appears to be missing the value for these many requests!. This is happening due to our cache read is not thread safe and will be like this mostly:

 
if(cache != null)
 {
   //read from the cache
 }
else if(cache == null)
 {
   //read from the DB and then add to cache
 }

so when concurrent requests hits at if block for the first time, cache will be null and going to hit the DB at the same time. This is obvious as the code is not thread safe. To make it thread safe we use lock

 
static readonly object _object = new object(); 
if (cache != null)
 {
	//return from the cache
 }
else if(cache == null)
 {
     lock(_object)
	{		

		//again try to read from the cache as by the time there is a possibility that cache can be set by a thread which was first inside this else if block
		//the later threads waiting outside the lock section and in this else if block can read it from the cache object than from DB once the lock is 
		//released by the thread which was first obtained the lock in the else if block and read the value from DB
		if(cache != null)
		  {
			object value = (object) cache[key];			
			//RuntimeContext.Get(cachekey);			
		  }
		if(cache == null)
		  {
			//read from the DB
			//Add the key & value to cache
		  }
	}
 }

CAUTION: This approach can backfire and is not a recommended one as I have seen places where after implementing this change the throughput of the application got worse than earlier even though DB hits not happening and cache working but so many threads were waiting in parallel for the lock. So need to analyse the performance of the application after making this change if we get good performance make the changes, otherwise need to find a better approach than this one. I am yet to find it, will update this once I know it.

Posting Concurrent HTTP requests Using Threading

2017-10-18

Using Threads namespace in .net framework we can trigger the concurrent HTTP requests to server. True concurrency can be achieved only when there is more than 1 CPU otherwise it's only a virtual thing that is achieved using swtiching b/w each threads by a single CPU.

A different note about Threading: Threading is useful only when the operation task involved in the threading method is I/O bound or wait for other resources involved. If it's only computational then Threading leverage no advantage & can backfire since there is cost for context switching b/w each threads.


static void Main(string[] args)
        {
while (true)
            {
                List<Thread> lstThreads = new List<Thread>();

                /*
                Thread objThread1 = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                lstThreads.Add(objThread1);

                Thread objThread2 = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                lstThreads.Add(objThread2);

                Thread objThread3 = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                lstThreads.Add(objThread3);

                Thread objThread4 = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                lstThreads.Add(objThread4);


                string fileLocation = @"D:\Asif\JIRA\NEO\Interface Migration\Sprint14\NEORND-3630\Meera\DAO Error\xml4DCRQ.xml";


                objThread1.Start(File.ReadAllText(string.Format("{0}\\{1}", fileLocation, "RTAV_Local_Series1.xml")));
                objThread2.Start(File.ReadAllText(string.Format("{0}\\{1}", fileLocation, "RTAV_Local_Series2.xml")));
                objThread3.Start(File.ReadAllText(string.Format("{0}\\{1}", fileLocation, "RTAV_Local_Series3.xml")));
                objThread4.Start(File.ReadAllText(string.Format("{0}\\{1}", fileLocation, "RTAV_Local_Series4.xml")));
                */

                string fileLocation = @"D:\JIRA\NEO\Sundarbans\Sprint20\NEORND-7568 [Search Connector] Load test optimized codebase\AvailRQMultiPropertySearchRQ.xml";
                for (int i = 1; i <= 30; i++)
                {
                    Thread objThread = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                    lstThreads.Add(objThread);
                    objThread.Start(File.ReadAllText(fileLocation));
                }


                int ctr = 1;
                foreach (var thread in lstThreads)
                {
                    thread.Join();

                    if (ctr == lstThreads.Count)
                    {
                        Console.WriteLine("All HDC threads finished executing");
                        goto EndWhile;
                    }
                    ctr++;
                }
            }
        EndWhile:
            Console.WriteLine("Press Any key to exit");
            Console.ReadLine();
}
static void DeadLockWithHotelDescriptiveContentNotifRQUpdate(object payload)
        {
            string xmlPayload = (string)payload;
            string response_text = string.Empty;
            try
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                System.Net.ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;

                //string url = "https://hotfix.hbsconnect.com/app/dm/xml/xml4test";
                string url = "http://127.0.0.1:5000/Search";
                //string url = "http://localhost/app/dm/xml/xml4test";

                HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(url);
                //-------GETTING WEBPROXY OF LOCAL MACHINE==========//
                WebProxy proxy = (WebProxy)WebProxy.GetDefaultProxy();

                if (proxy.Address != null)
                {
                    proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                    WebRequest.DefaultWebProxy = new System.Net.WebProxy(proxy.Address, proxy.BypassProxyOnLocal, proxy.BypassList, proxy.Credentials);
                }
                //request.Proxy = proxy;
                //----PROXY SET UP===========//


                byte[] bytes = Encoding.UTF8.GetBytes(xmlPayload);
                request.Method = "POST";
                request.Accept = "*/*";
                request.Timeout = 360000; //=6mnts

                request.ContentType = "text/xml"; // text/plain
                request.KeepAlive = false;
                request.ContentLength = bytes.Length;
                request.ProtocolVersion = HttpVersion.Version10;
                //request.ServicePoint.Expect100Continue = true;

                Stream stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Flush();


                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    /* 
                    Stream responseStream = response.GetResponseStream();
                    StreamReader Reader = new StreamReader(responseStream, Encoding.Default);
                    response_text = Reader.ReadToEnd();
                    */

                    Stream response_stream = response.GetResponseStream();
                    byte[] byteStream = new byte[512];
                    StringBuilder sbResponse = new StringBuilder();
                    System.Text.Encoding utfEncode = System.Text.Encoding.GetEncoding("utf-8");
                    int byteCount = response_stream.Read(byteStream, 0, 512);
                    while (byteCount > 0)
                    {
                        sbResponse.Append(utfEncode.GetString(byteStream, 0, byteCount));
                        try
                        {
                            byteCount = response_stream.Read(byteStream, 0, 512);
                        }
                        catch
                        {
                            //Micros don't terminate their output stream correctly and just close the connection resulting in an exception at our end
                            byteCount = 0;
                        }
                    }
                    response_text = sbResponse.ToString();
                    if (response_text == string.Empty) response_text = response.StatusCode.ToString();
                }
                stream.Close();
            }
            catch (WebException webEx)
            {
                //throw webEx;
            }
            catch (Exception ex)
            {
                //throw ex;
            }
        }

How to capture the network communication details b/w Application & client

2017-01-15

Sometimes one might need to know what is occurring at network level even before the user request reaches the application level. For instance if you are receiving only an exception at application level such as like this:
Exception is : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. Source is : System Stack trace is : at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) at System.Net.HttpWebRequest.GetRequestStream()

And at n/w team at both parties says everthing is normal i.e. at the reciving server(here it's our server) & sending server(here customer's server).

To know exactly what is causing this exception, we will get more details about this kind of exceptions by enabling n/w trace. This can be done at the App.config file of the AppServer. You will find the details of n/w communication in the path you mentioned in the App.config, here: c:\network.log​



    
      
        
          
           
      
        
          
        
      
        
          
        
    
    
      
      
      
    
    
      
    
    
  

In the end, by looking at the captured log it seems to be that the certificate of the customer was not accepted by the application server. I could find this information in the trace log:


System.Net.Sockets Verbose: 0 : [0940] 00000010 : AE AE DA C7 BF 8B 75 D5-5B EA 88 2E 73 9A 5C 10 : ......u.[...s.\.
System.Net.Sockets Verbose: 0 : [0940] 00000020 : 76 EF 5A C7 DC 86 78 CF-C6 88 36 F0 5C 95 E0 B9 : v.Z...x...6.\...
System.Net.Sockets Verbose: 0 : [0940] 00000030 : 57 06 03 43 A0 51 7A 38-D1 AA 9A E1 B9 62 E3 4F : W..C.Qz8.....b.O
System.Net.Sockets Verbose: 0 : [0940] 00000040 : 63 0A 31 DE 47 6F 81 0C-40 AB EA B4 3F 55 09 6B : c.1.Go..@...?U.k
System.Net.Sockets Verbose: 0 : [0940] 00000050 : 79 07 C8 FE D0 DD 53 61-35 14 D2 76 D4 24 C0 95 : y.....Sa5..v.$..
System.Net.Sockets Verbose: 0 : [0940] 00000060 : 1A 79 CA 59 3F EB C7 06-FE 72 00 15 E3 AB F2 E7 : .y.Y?....r......
System.Net.Sockets Verbose: 0 : [0940] 00000070 : 1E 10 5C AB 64 3D 6C FC-33 76 7A 06 61 45 9C 27 : ..\.d=l.3vz.aE.'
System.Net.Sockets Verbose: 0 : [0940] 00000080 : D2 44 18 F5 41 9B E9 BE-86 EF 15 7D E4 45 1C 8A : .D..A......}.E..
System.Net.Sockets Verbose: 0 : [0940] 00000090 : 38 30 8F 56 74 F2 E9 ED-7C 9E AB 1D 0D 03 F1 1B : 80.Vt...|.......
System.Net.Sockets Verbose: 0 : [0940] 000000A0 : 3A ED B4 DF 42 7C AF E6-21 66 B2 4E CA 7B 59 3E : :...B|..!f.N.{Y>
System.Net.Sockets Verbose: 0 : [0940] 000000B0 : 3B 8C D8 66 2A 0C BD 9C-18 DE 7A 42 D2 6B E7 C6 : ;..f*.....zB.k..
System.Net.Sockets Verbose: 0 : [0940] 000000C0 : C1 E7 6D 6E 2E E6 A6 E2-78 3C FD 58 3F 9F F3 23 : ..mn....x<.X?..#
System.Net.Sockets Verbose: 0 : [0940] 000000D0 : 5E CC 66 52 1F 9A EC B1-85 91 C0 A7 34 E8 F0 DC : ^.fR........4...
System.Net.Sockets Verbose: 0 : [0940] 000000E0 : 7D 86 2D C5 DF A2 9C BE-69 35 74 52 76 4D C1 44 : }.-.....i5tRvM.D
System.Net.Sockets Verbose: 0 : [0940] 000000F0 : 3E 3B 83 9F 8D 2F 3B C6-B2 A8 7F 42 CD BD 22 4A : >;.../;....B.."J
System.Net.Sockets Verbose: 0 : [0940] 00000100 : AF 5E 01 33 D0 19 FF 54-98 81 52 14 03 01 00 01 : .^.3...T..R.....
System.Net.Sockets Verbose: 0 : [0940] 00000110 : 01 16 03 01 00 20 07 F4-8E BA 46 DD 38 EF 25 16 : ..... ....F.8.%.
System.Net.Sockets Verbose: 0 : [0940] 00000120 : 88 77 4D 96 84 89 D8 33-F0 94 D1 89 81 C0 6F B1 : .wM....3......o.
System.Net.Sockets Verbose: 0 : [0940] 00000130 : FF FE 51 3F D4 85                               : ..Q?..
System.Net.Sockets Verbose: 0 : [0940] Exiting Socket#10261382::Send()  -> 310#310
System.Net.Sockets Verbose: 0 : [0940] Socket#10261382::Receive()
System.Net.Sockets Verbose: 0 : [0940] Data from Socket#10261382::Receive
System.Net.Sockets Verbose: 0 : [0940] 00000000 : 14 03 01 00 01                                  : .....
System.Net.Sockets Verbose: 0 : [0940] Exiting Socket#10261382::Receive()  -> 5#5
System.Net.Sockets Verbose: 0 : [0940] Socket#10261382::Receive()
System.Net.Sockets Verbose: 0 : [0940] Data from Socket#10261382::Receive
System.Net.Sockets Verbose: 0 : [0940] 00000005 : 01                                              : .
System.Net.Sockets Verbose: 0 : [0940] Exiting Socket#10261382::Receive()  -> 1#1
System.Net Information: 0 : [0940] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 1a83060:4f01a90, targetName = 208.65.59.102, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [0940] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=ContinueNeeded).
System.Net.Sockets Verbose: 0 : [0940] Socket#10261382::Receive()
System.Net.Sockets Verbose: 0 : [0940] Data from Socket#10261382::Receive
System.Net.Sockets Verbose: 0 : [0940] 00000000 : 16 03 01 00 20                                  : .... 
System.Net.Sockets Verbose: 0 : [0940] Exiting Socket#10261382::Receive()  -> 5#5
System.Net.Sockets Verbose: 0 : [0940] Socket#10261382::Receive()
System.Net.Sockets Verbose: 0 : [0940] Data from Socket#10261382::Receive
System.Net.Sockets Verbose: 0 : [0940] 00000005 : 2F F4 5F 34 94 31 43 6B-E8 9E DF 73 F2 38 40 11 : /._4.1Ck...s.8@.
System.Net.Sockets Verbose: 0 : [0940] 00000015 : 0B CD EB 74 FF 79 3E E9-09 FC 70 40 1E EA 5F 86 : ...t.y>...p@.._.
System.Net.Sockets Verbose: 0 : [0940] Exiting Socket#10261382::Receive()  -> 32#32
System.Net Information: 0 : [0940] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 1a83060:4f01a90, targetName = 208.65.59.102, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [0940] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=OK).
System.Net Information: 0 : [0940] Remote certificate: [Version]
  V3

[Subject]
  CN=*.loewshotels.com, O=LOEWS HOTELS HOLDING CORPORATION, L=New York, S=New York, C=US
  Simple Name: *.loewshotels.com
  DNS Name: loewshotels.com

[Issuer]
  CN=GeoTrust SSL CA - G3, O=GeoTrust Inc., C=US
  Simple Name: GeoTrust SSL CA - G3
  DNS Name: GeoTrust SSL CA - G3

[Serial Number]
  6FE9FB525426DDBB0A93A92A3C1E92AB

[Not Before]
  10/1/2015 12:00:00 AM

[Not After]
  9/30/2016 11:59:59 PM

[Thumbprint]
  72D2C02328C86D8CFC95A0BA8ADA9D441E52D9AD

[Signature Algorithm]
  sha256RSA(1.2.840.113549.1.1.11)

[Public Key]
  Algorithm: RSA
  Length: 2048
  Key Blob: 30 82 01 0a 02 82 01 01 00 ea 70 dd ae 1d df 72 35 54 60 22 ee 31 37 49 b9 3a 5d f3 69 9e 60 d0 4a 24 3d e7 62 47 ce 93 af 1e 92 63 03 eb 2e 64 2a a2 01 c5 c1 14 17 44 1e 31 01 45 3e 95 57 d1 0d b4 9b 2d ad 7a 1b 60 1c 8a 77 e9 c9 69 fa ce f1 1d 39 be 57 5c 19 02 19 13 ed 58 56 15 fa 91 f5 99 75 43 3f cf 61 ed 2f ab d6 7b bf 37 8b 31 2f 8a 13 a8 7b b0 65 35 b2 ce f7 b8 ee 7d fc 39 85....
System.Net Information: 0 : [0940] SecureChannel#17043416 - Remote certificate has errors:
System.Net Information: 0 : [0940] SecureChannel#17043416 -  Certificate name mismatch.
System.Net Information: 0 : [0940] SecureChannel#17043416 - Remote certificate was verified as invalid by the user.
System.Net.Sockets Verbose: 0 : [0940] Socket#10261382::Dispose()
System.Net Error: 0 : [0940] Exception in the HttpWebRequest#44419000:: - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
System.Net Error: 0 : [0940] Exception in the HttpWebRequest#44419000::EndGetRequestStream - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Compare 2 strings by ignoring the case

Check for case insensitive match for the word BAR1 to BAR99

i.e. possible list of matches in this range are:

BAR1, bar1, BAR2,BAR3,BAR10,...BAR99,BaR99


static void IsMatchFound()
        {
            string pattern = @"^BAR([1-99]{1,2}|10|20|30|40|50|60|70|80|90)$";
            Console.WriteLine("Enter input:");
            string input = Console.ReadLine();
            if (input == "C")
            {
                Console.Clear();
            }
            Match result = Regex.Match(input, pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (result.Success)
            {

                Console.WriteLine("Valid");
            }
            else
            {
                Console.WriteLine("Invalid");
            }
        }​

Trim Guest Title if there is Title is present in the name using Regex

Requirement is ​remove the title from the guest name if there is title present in the name. Set of possible titles is already known & is stored in an array each one seperated by a seperator |
Title List: Mr|Mrs|Mr.|Dr|Dr.
Conditions to remove title from the guest name:
1. If the title is found in the above Title list
2. Match of title found(case insensitive)
Example: Mr Rama Murthy
after trimming: Rama Murthy
Example: Mr.RemaSankar
after trimming: RemaSankar
Code:
static void GuestNameUtility(string pGuestName, List pTitles)
        {
            //Split(null); equals white space; Refer:http://stackoverflow.com/questions/6111298/best-way-to-specify-whitespace-in-a-string-split-operation
            string[] result = pGuestName.Split(null);
            string pattern = string.Empty;
            StringBuilder sbPattern = new StringBuilder(string.Empty);
            int dotIndex = 0;
            string titleWhiteSpaceTrimmed = string.Empty;
            string[] splitArray = null;
            string afterRemovingTitle = string.Empty;

            for (int i = 0; i < pTitles.Count; i++)
            {
                if (sbPattern.Length > 0)
                    sbPattern.Append("|");
                if (pTitles[i].Contains('.'))
                {
                    //We have to trim any whitespace in the Title as we are going to compare Title with the title 
     //found in the guestname where there also we are trimming the whitespace
                    //If this trimming is not used in both sides (i.e. while reaing the Titles given in IT settings & 
     //in reading guestName section by removing whitespace in the guestName section.)
                    //we will face issues while matching with whitespaces
                    titleWhiteSpaceTrimmed = pTitles[i].Trim();
                    dotIndex = titleWhiteSpaceTrimmed.IndexOf('.');
                    //Need to escape period(i.e. '.') as it should also be considered for a match. Escape the period otherwise 
     //it will be treated as period(.) has special meaning in Regex
                    sbPattern.Append(string.Format("{0}", titleWhiteSpaceTrimmed.Substring(0, dotIndex) + Regex.Escape(".")));
                }
                else
                {
                    sbPattern.Append(string.Format("{0}", pTitles[i].Trim()));
                }
            }
            //Need to match only the exact Titles with start & ending should match by using ^(start) & $(end)
            //So for example ^(Mr|Mrs.|Mrs |Master)$ is given Title patterns & a guestname with Mrs Srimati Gowri 
   //comes Mrs should be matched exactly with 'Mrs' & not with 'Mr'
            pattern = string.Format("^({0})$", sbPattern.ToString());
            if (result.Length == 0)
            {
                m_guestLastName = pGuestName;
            }
            else
            {
                m_guestLastName = result[result.Length - 1];
                StringBuilder sbFirstName = new StringBuilder(string.Empty);
                for (int i = 0; i <= result.Length - 2; i++)
                {
                    //If the iterating guest name part has period(.), we need to split by period(.) & compare for a match 
                    //This logic is required as by this only we can find a match if the title is coming along with guestname 
     //wihtout any space. Example is:Mr.Asif Abdulla
                    //If this logic is not used then we will not be able to identify the title match for 'Mr.' 
     //in the guest name:Mr.Asif Abdulla


                    if (result[i].Contains('.'))
                    {
                        splitArray = result[i].Split('.');
                        splitArray[0] = string.Format("{0}.", splitArray[0]);
                    }
                    else
                    {
                        splitArray = new string[1];
                        splitArray[0] = result[i];
                    }
                    foreach (string splitArrayItem in splitArray)
                    {
                        Match matchResult = Regex.Match(splitArrayItem, pattern, RegexOptions.IgnoreCase);
                        if (matchResult.Success)
                        {
                            afterRemovingTitle = Regex.Replace(splitArrayItem, pattern, string.Empty, RegexOptions.IgnoreCase);
                            if (!string.IsNullOrEmpty(afterRemovingTitle))
                            {
                                if (sbFirstName.Length > 0)
                                    sbFirstName.Append(" ");
                                sbFirstName.Append(afterRemovingTitle);
                            }
                        }
                        else
                        {
                            if (sbFirstName.Length > 0)
                                sbFirstName.Append(" ");
                            sbFirstName.Append(splitArrayItem);
                        }
                    }
                }
                m_guestFirstName = sbFirstName.ToString();
                if (string.IsNullOrEmpty(m_guestFirstName))
                    m_guestFirstName = m_guestLastName;
            }
        }​

Breakpoint not hitting- How to troubleshoot

2017-01-14

Check the location of debug symbols(Debug>Module) of the assembly & verify it's picking from location has the latest dll file version. The location of the assembly probably will be "Temporary ASP.NET Folder" for web applications. And check the "Symbol load Information" against the assembly from the Module window which shows where the assembly is looking for the debug symbol file. This file should match with the dll, then only break point will hit in debug mode. If it cannot find matching PDB file, then check the assembly in the "Temporary ASP.NET Folder" is the one which is latest one you just build.  You can do check by looking at timestamp of each assemblies, if not matching then it's not then it's the old assemlby somehow copied to this "Temporary ASP.NET Folder" & that is making this issue. So we need to find out why this happend i.e. why the lates DLL file is not copied to "Temporary ASP.NET Folder". To find out this, check for a search of this assembly for its duplicates, you should find somewhere in the IIS you have hosted its duplicate!. Delete this duplicate & now clear the "Temporary ASP.NET Folder" & now debug must work.

 Note the location of PDB file is added in the assembly of the project itself. So this check for matching of PDB file if failed is itself hinting that the assembly you just build is not the one present in the "Temporary ASP.NET Folder"

Value Type & Reference Types

2013-04-13


There are only 2 kinds of data types in .net framework:
  1. Value Type and
  2. Reference Type
What is a value type:

A type which is allocated in the stack area of memory, meaning that when the scope of the variable is over, it's cleaned up.  

What is a reference type:

When an object is allocated from the managed heap, the new operator returns the memory address of the object. You usually store this address in a variable. This is called a reference type variable because the variable does not actually contain the object's bits; instead, the variable refers to the object's bits. 

Some Differences & Comparision B/w these 2 Types:


  1. Reference type variables contain the memory address of objects in the heap. By default, when a reference type variable is created, it is initialized to null, indicating that the reference type variable doesn't currently point to a valid object. Attempting to use a null reference type variable causes a NullReferenceException exception. By contrast, value type variables always contain a value of the underlying type. By default, all members of the value type are initialized to zero. It is not possible to generate a NullReferenceException exception when accessing a value type.
  2.  There are some performance issues to consider when working with reference types. First, the memory must be allocated from the managed heap, which could force a garbage collection to occur. Second, reference types are always accessed via their pointers. So every time your code references any member of an object on the heap, code must be generated and executed to dereference the pointer in order to perform the desired action. This adversely affects both size and speed.
  3. When you assign a value type variable to another value type variable, a copy of the value is made. When you assign a reference type variable to another reference type variable, only the memory address is copied.
          Because of the previous point, two or more reference type variables may refer to a single object in the heap. This allows operations on one variable to affect the object referenced by the other variable. On the other hand, value type variables each have their own copy of the object's data, and it is not possible for operations on one value type variable to affect another.value type is better in performance, because the variable contains the object directly and there is no need of a reference. When possible, you should use value types instead of reference types because your application's performance will be better.
  4. When type is passed as a reference to the function both members of the type & the type itself can be changed, where as when passed as a value type only the the members of the type can be changed. It's not possible to change the type of reference object to a new address in a function with a value parameter where as in a function with a reference type parameter it's possible to change the members as well as to a new address for the current input.
  5. Reference parameters don't pass the values of the variables used in the function member invocation - they use the variables themselves. Rather than creating a new storage location for the variable in the function member declaration, the same storage location is used, so the value of the variable in the function member and the value of the reference parameter will always be the same.


Some examples to illustrate the above points:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ValueTypeRefTypeDiff
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("------ValueType Lessons------");
                Product apple = new Product("Apple", 150);
                Console.WriteLine("Created a new product");
                Console.WriteLine(string.Format("The product name:{0} , Rate:{1}", apple.ProductName,  apple.Rate));
    
                Console.WriteLine();
                Console.WriteLine();
    
                Console.WriteLine("Passing this product as value type to the function");
                Console.WriteLine("Trying to change the properties of product...");
                ValueTypeChangeProperties(apple);
                Console.WriteLine(string.Format("The product name:{0} , Rate:{1}", apple.ProductName,  apple.Rate));
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Lesson1:");
                Console.WriteLine("Properties of the product changed...");
    
                Console.WriteLine();
                Console.WriteLine();
    
                Console.WriteLine("Passing this product as value type to the function");
                Console.WriteLine("Trying to change the properties of product & then Product itself...");
                ValueTypeChangePropertiesAndProductToo(apple);
                Console.WriteLine(string.Format("The product name:{0} , Rate:{1}", apple.ProductName,  apple.Rate));
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Lesson2:");
                Console.WriteLine("Only properties changed no change in product...");
    
                Console.WriteLine();
                Console.WriteLine();
    
                
                Console.WriteLine("------ReferenceType Lessons------");
    
                Product objapple = new Product("Apple", 150);
                Console.WriteLine("Created a new product");
                Console.WriteLine(string.Format("The product name:{0} , Rate:{1}", objapple.ProductName, objapple.Rate));
    
                Console.WriteLine();
                Console.WriteLine();
    
                Console.WriteLine("Passing this product as reference type to the function");
                Console.WriteLine("Trying to change the properties of product...");
                ReferenceTypeChangeProperties(ref objapple);
                Console.WriteLine(string.Format("The product name:{0} , Rate:{1}", objapple.ProductName, objapple.Rate));
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Lesson1:");
                Console.WriteLine("Properties of the product changed...");
    
                Console.WriteLine();
                Console.WriteLine();
    
                Console.WriteLine("Passing this product as reference type to the function");
                Console.WriteLine("Trying to change the properties of product & then Product itself...");
                ReferenceTypeChangePropertiesAndProdcutToo(ref objapple);
                Console.WriteLine(string.Format("The product name:{0} , Rate:{1}", objapple.ProductName, objapple.Rate));
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Lesson2:");
                Console.WriteLine("Both properties as well as product can be changed...");
    
                Console.ReadLine();
            }
    
    
    
            private static void ValueTypeChangeProperties(Product p)
            {
                p.Rate = 30;
                
            }
    
            private static void ValueTypeChangePropertiesAndProductToo(Product p)
            {
                p.Rate = 43;
                p = new Product("Orange",40);
            }
    
            private static void ReferenceTypeChangeProperties(ref Product p)
            {
                p.Rate = 20;
            }
    
            private static void ReferenceTypeChangePropertiesAndProdcutToo(ref Product p)
            {
                p.Rate = 20;
                p = new Product("Cuccumber", 40);
            }
        }
    
        class Product
        {
            public string ProductName { get; set; }
                    public decimal Rate { get; set; }
            public Product( string name,decimal price )
            {
                
                Rate = price;
                ProductName = name;
            }
        }
    }
    

    Parameter Passing


    There are four different kinds of parameters in C#: value parameters (the default), reference parameters (which use the ref modifier), output parameters (which use the out modifier), and parameter arrays (which use the params modifier). You can use any of them with both value and reference types. When you hear the words "reference" or "value" used (or use them yourself) you should be very clear in your own mind whether you mean that a parameter is a reference or value parameter, or whether you mean that the type involved is a reference or value type. If you can keep the two ideas separated, they're very simple.


    1. Value parameters With their Type as Reference Type:

    By default, parameters are value parameters. This means that a new storage location is created for the variable in the function member declaration, and it starts off with the value that you specify in the function member invocation. If you change that value, that doesn't alter any variables involved in the invocation. For instance, if we have:
    class ValueTypeRefTypeExercises
        {
            static void Main(string[] args)
            {
                StringBuilder y = new StringBuilder();
                y.Append("Hello");
                Foo(y);
                Console.WriteLine(y == null);
    
    
                Console.ReadLine();
            }
    
            static void Foo(StringBuilder x)
            {
                x = null;
            }
        }
    




    As discussed in the first example code it's not possible to change the type of reference object to a new address in a function with a value parameter.

    The value of y isn't changed just because x is set to null. Remember though that the value of a reference type variable is the reference - if two reference type variables refer to the same object, then changes to the data in that object will be seen via both variables. For example:


    class ValueTypeRefTypeExercises
        {
            static void Main(string[] args)
            {
                StringBuilder y = new StringBuilder();
                y.Append("Hello");
                Foo(y);
                Console.WriteLine(y);
    
    
                Console.ReadLine();
            }
    
            static void Foo(StringBuilder x)
            {
                x.Append(" world");
            }
        }
    

    2. Value parameters With their Type as Value Type:

    Now consider what happens when value types are passed by value. As I said before, the value of a value type variable is the data itself. Using the previous definition of the struct IntHolder, let's write some code similar to the above:

    void Foo (IntHolder x)
    {
        x.i=10;
    }
    
    ...
    
    IntHolder y = new IntHolder();
    y.i=5;
    Foo (y);
    Console.WriteLine (y.i);
    

    Output: 5

    When Foo is called, x starts off as a struct with value i=5. Its i value is then changed to 10. Foo knows nothing about the variable y, and after the method completes, the value in y will be exactly the same as it was before (i.e. 5).


    3. Ref Parameter with their Type as Reference Type:

    Reference parameters don't pass the values of the variables used in the function member invocation - they use the variables themselves. Rather than creating a new storage location for the variable in the function member declaration, the same storage location is used, so the value of the variable in the function member and the value of the reference parameter will always be the same. Reference parameters need the ref modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something by reference. Let's look at our previous examples, just changing the parameter to be a reference parameter:

    void Foo (ref StringBuilder x)
    {
        x = null;
    }
    
    ...
    
    StringBuilder y = new StringBuilder();
    y.Append ("hello");
    Foo (ref y);
    Console.WriteLine (y==null);
    

    Output: True

    4. Ref Parameter with their Type as Value Type:

    Now consider the struct code we had earlier, but using reference parameters:


    void Foo (ref IntHolder x)
    {
        x.i=10;
    }
    
    ...
    
    IntHolder y = new IntHolder();
    y.i=5;
    Foo (ref y);
    Console.WriteLine (y.i);
    
    Output: 10

    The two variables are sharing a storage location, so changes to x are also visible through y, so y.i has the value 10 at the end of this code.


    what is the difference between passing a value object by reference and a reference object by value? 

    You may have noticed that the last example, passing a struct by reference, had the same effect in this code as passing a class by value. This doesn't mean that they're the same thing, however. Consider the following code:

    void Foo (??? IntHolder x)
    {
        x = new IntHolder();
    }
    
    ...
    
    IntHolder y = new IntHolder();
    y.i=5;
    Foo (??? y);
    

    In the case where IntHolder is a struct (i.e. a value type) and the parameter is a reference parameter (i.e. replace ??? with ref above), y ends up being a new IntHolder value - 

    i.e. y.i is 0. In the case where IntHolder is a class (i.e. a reference type) and the parameter is a value parameter (i.e. remove ??? above), the value of y isn't changed - it's 

    a reference to the same object it was before the function member call. This difference is absolutely crucial to understanding parameter passing in C#, and is why I believe it is highly confusing to say that objects are passed by reference by default instead of the correct statement that object references are passed by value by default.

    Conclusions:
    1. When designing your own API, I would strongly advise you to almost never use ref or out parameters. They can be useful occasionally, but usually they're an indication that you're trying to return multiple values from a single method, which is often better done with a type specifically encapsulating those values, or perhaps a Tuple type if you're using .NET 4. There are exceptions to this rule, of course, but it's a good starting point.

    2. When possible, you should use value types instead of reference types because your application's performance will be better. In particular, you should declare a type as a value type if all of the following are true:
    The type acts like a primitive type.
    The type doesn't need to inherit from any other type.
    The type will not have any other types derived from it.
    Objects of the type are not frequently passed as method arguments since this would cause frequent memory copy operations, hurting performance. 

    References:

    1. .NET: Type Fundamentals by Jeffrey Richter
    2. Parameter passing in C# by Jon Skeet

    How to select Distinct values from Datatable & update the records

    2013-02-11

    Private Sub ProcessReturnIdentifierInResponse(ByRef dtAvailResult As DataTable)
                Try
    Dim filterCondition As StringBuilder = New StringBuilder(String.Empty)
    Dim returnIdentifierCounter As Integer = 1
    Dim rowsWithUniqueReturnIdentifierValue() As DataRow = dtAvailResult.DefaultView.ToTable(True,AirlineAvailibilityConstants.Avail_ReturnIdentifier).Select()
    For Each uniqueReturnIdentifierRecord As DataRow In rowsWithUniqueReturnIdentifierValue
    filterCondition.Clear()
    filterCondition.Append(AirlineAvailibilityConstants.Avail_ReturnIdentifier)
    filterCondition.Append("=")
    filterCondition.Append(uniqueReturnIdentifierRecord(AirlineAvailibilityConstants.Avail_ReturnIdentifier).ToString())
    Dim filteredRows() As DataRow = DTAvailResponse.Select(filterCondition.ToString())
    For Each recordToUpdate As DataRow In filteredRows
    recordToUpdate(AirlineAvailibilityConstants.Avail_ReturnIdentifier) = returnIdentifierCounter
    returnIdentifierCounter += 1
    Next
    
    Next
    
                Catch ex As Exception
    
                End Try
            End Sub
    

    Catching Web Exceptions While Calling Web Services

    2013-02-08

    try
    {
    
    }
    catch WebException
    
    catch Exception
    

    Updating an item in the collection

    2012-09-06

    This method is an easy way(i.e with few lines of code) to update an object in a collection. This can be used when you want to update an existing item in a collection with some values read from another object in another collection and all other fields of the existing item remaining same.

    Dummy Code:
    Dim existingObject = ExisitngCollection(itemIndex)
    For Each foo In Foos
    existingObject.Property1 = foo.Property1
    existingObject.Property2 = foo.Property2
    Next



    Real Example:

    Private Function UpdateRoundingValue(ByVal ObjAvailabilityHandlerProcessMergeResponseDom As ClsAvailabilityHandlerProcessMergeResponseDom, ByVal ObjHtlRoundingEntity As ClsHtlRoundingEntity) As ClsAvailabilityHandlerProcessMergeResponseDom
                Dim hotelCounter As Int16 = 0
                Dim roomTypeCounter As Int16 = 0
                Dim roomRateCounter As Int16 = 0
                Try
                  
                    hotelCounter = 0
                    For Each RoundingHotel As ClsHtlRoundingHotel In ObjHtlRoundingEntity.ObjHtlRoundingHotels
                        Dim hotelToUpdate = ObjAvailabilityHandlerProcessMergeResponseDom.ObjClsHtlDomAvltRes.ObjHtlDomAvltResHotels(hotelCounter)
                        roomTypeCounter = 0
                        For Each RoundingRoomType As ClsHtlRoundingRoomType In RoundingHotel.ObjHtlRoundingRoomTypes
                            Dim roomTypeToUpdate = hotelToUpdate.ObjHtlDomAvltResRoomTypes(roomTypeCounter)
                            With roomTypeToUpdate
                                .GrossFare = RoundingRoomType.GrossFare
                                .BaseFare = RoundingRoomType.BaseFare
                                .NetFare = RoundingRoomType.NetFare
                                .SupplierFare = RoundingRoomType.SupplierFare
                                .CustomerFare = RoundingRoomType.CustomerFare
                                roomRateCounter = 0
                                For Each RoundingRoomRate As ClsHtlRoundingRoomRate In RoundingRoomType.HtlRoundingRoomRates
                                    Dim roomRateToUpdate = roomTypeToUpdate.HtlDomAvltResRoomRates(roomRateCounter)
                                    With roomRateToUpdate
                                        .AdultRate = RoundingRoomRate.AdultRate
                                        .ChildRate = RoundingRoomRate.ChildRate
                                        .ExtraRate = RoundingRoomRate.ExtraRate
                                        .Tax = RoundingRoomRate.Tax
                                        .ServiceTax = RoundingRoomRate.ServiceTax
                                        .ServiceCharge = RoundingRoomRate.ServiceCharge
                                        .OtherCharges = RoundingRoomRate.OtherCharges
                                        .TransactionFee = RoundingRoomRate.TransactionFee
                                        .Commission = RoundingRoomRate.Commission
                                        .TDSOnCommission = RoundingRoomRate.TDSOnCommission
                                        .Discount = RoundingRoomRate.Discount
                                        .TDSOnDiscount = RoundingRoomRate.TDSOnDiscount
                                        .SupplierFare = RoundingRoomRate.SupplierFare
                                        .AgentAddOnMarkup = RoundingRoomRate.AgentAddOnMarkup
                                        .AgentAddOnDiscount = RoundingRoomRate.AgentAddOnDiscount
                                        .AgentTransactionFee = RoundingRoomRate.AgentTransactionFee
                                        .AgentMarkup = RoundingRoomRate.AgentMarkup
                                        .AgentDiscount = RoundingRoomRate.AgentDiscount
                                        .CustomerFare = RoundingRoomRate.CustomerFare
                                    End With
                                    roomRateCounter += 1
                                Next
    
                            End With
                            roomTypeCounter += 1
                        Next
                        hotelCounter += 1
                    Next
    
                Catch ex As Exception
                    Response.TransRemarks = ex.Message & "-" & ex.StackTrace
                    Response.TransStatus = True
                    Response.TransCode = "1111"
                    LogError(Reflection.MethodBase.GetCurrentMethod.DeclaringType.FullName, Reflection.MethodBase.GetCurrentMethod.Name, ex.Message & "-" & ex.StackTrace)
                Finally
                    UpdateRoundingValue = ObjAvailabilityHandlerProcessMergeResponseDom
                End Try
    
            End Function

    Write String Object to File And Read File content to String

    2012-01-04


    Reading File Content to a string variable


     dim sRequestXML as String  = File.ReadAllText("C:\Users\arun\Desktop\ModifiedTIReq.xml")



    Writing String to an XML File


    File.WriteAllText("E:\ASIF ABDULLA\Flight\LIVE BOOKING REQS\ROUNDTRIPSGBOOKINGREQ.xml", RequestXML)
    
    


    Namespace for File class is System.IO

    Reading Data from XML file

    2011-11-11

    Here is an example of reading data from an XML file in .net

    Sample XML Input


    <FLTIntAvltRes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <FLTIntAvltResFlights>
      <FLTIntAvltResOnwardFlights>
       <FLTIntAvltResFlightSegment>
        <ChannelCode>6E</ChannelCode>
        <FLTIntAvltResConnectionPoints>
         <FLTIntAvltResConnectionSegment>
          <FLTIntAvltResFlightDetails>
           <ArrivalAirportCode>BOM</ArrivalAirportCode>
           <DepartureAirportCode>BLR</DepartureAirportCode>
          </FLTIntAvltResFlightDetails>
          <FLTIntAvltResFareDetails>
           <GrossFare>18289</GrossFare>
           <NetFare>18289</NetFare>
          </FLTIntAvltResFareDetails>
          <FLTIntAvltResTaxDetails>
           <TotalTax>0</TotalTax>
          </FLTIntAvltResTaxDetails>
         </FLTIntAvltResConnectionSegment>
         <FLTIntAvltResConnectionSegment>
          <FLTIntAvltResFlightDetails>
           <FlightId>''</FlightId>
           <JourneyDuration>''</JourneyDuration>
          </FLTIntAvltResFlightDetails>
          <FLTIntAvltResFareDetails>
           <GrossFare>0</GrossFare>
           <NetFare>0</NetFare>
          </FLTIntAvltResFareDetails>
          <FLTIntAvltResTaxDetails>
           <TotalTax>0</TotalTax>
          </FLTIntAvltResTaxDetails>
         </FLTIntAvltResConnectionSegment>
        </FLTIntAvltResConnectionPoints>
       </FLTIntAvltResFlightSegment>
      </FLTIntAvltResOnwardFlights>
      <FLTIntAvltResReturnFlights>
       <FLTIntAvltResFlightSegment>
        <ChannelCode>6E</ChannelCode>
        <FLTIntAvltResConnectionPoints>
         <FLTIntAvltResConnectionSegment>
          <FLTIntAvltResFlightDetails>
           <FlightNo>82</FlightNo>
           <ArrivalDateTime>2011-11-25T04:25:00</ArrivalDateTime>
           <DepartureDateTime>2011-11-25T00:15:00</DepartureDateTime>
           <ArrivalAirportCode>BOM</ArrivalAirportCode>
          </FLTIntAvltResFlightDetails>
          <FLTIntAvltResFareDetails>
           <GrossFare>17049</GrossFare>
           <NetFare>17049</NetFare>
          </FLTIntAvltResFareDetails>
          <FLTIntAvltResTaxDetails>
           <TotalTax>0</TotalTax>
          </FLTIntAvltResTaxDetails>
         </FLTIntAvltResConnectionSegment>
         <FLTIntAvltResConnectionSegment>
          <FLTIntAvltResFlightDetails>
           <ArrivalDateTime>2011-11-25T15:30:00</ArrivalDateTime>
           <DepartureDateTime>2011-11-25T13:45:00</DepartureDateTime>
           <ArrivalAirportCode>BLR</ArrivalAirportCode>
          </FLTIntAvltResFlightDetails>
          <FLTIntAvltResFareDetails>
           <GrossFare>0</GrossFare>
           <NetFare>0</NetFare>
          </FLTIntAvltResFareDetails>
          <FLTIntAvltResTaxDetails>
           <TotalTax>0</TotalTax>
          </FLTIntAvltResTaxDetails>
         </FLTIntAvltResConnectionSegment>
        </FLTIntAvltResConnectionPoints>
       </FLTIntAvltResFlightSegment>
      </FLTIntAvltResReturnFlights>
     </FLTIntAvltResFlights>
    </FLTIntAvltRes>
    
    

    Reading part
    ---------------

    Dim availablityReponseXML As XmlDocument = New XmlDocument()
            availablityReponseXML.Load("E:\ASIF ABDULLA\Flight\Benzy Proxy\SGInternational\6EROUNDTRIP_CONNECTION_AVAILINTRESPONSE.xml")
    
    Dim OnwardConnectionLegs As XmlNodeList = availablityReponseXML.SelectNodes("/FLTIntAvltRes/FLTIntAvltResFlights/FLTIntAvltResOnwardFlights/FLTIntAvltResFlightSegment/FLTIntAvltResConnectionPoints/FLTIntAvltResConnectionSegment")
    
            Dim returnConnectionLegs As XmlNodeList = availablityReponseXML.SelectNodes("/FLTIntAvltRes/FLTIntAvltResFlights/FLTIntAvltResReturnFlights/FLTIntAvltResFlightSegment/FLTIntAvltResConnectionPoints/FLTIntAvltResConnectionSegment")
    
    
            For Each connection As XmlNode In OnwardConnectionLegs
                Dim fareLeg As XmlNode = connection.ChildNodes(1)
                netFare += Convert.ToDecimal(fareLeg("NetFare").InnerText)
            Next
    
            For Each connection As XmlNode In returnConnectionLegs
                Dim fareLeg As XmlNode = connection.ChildNodes(1)
                netFare += Convert.ToDecimal(fareLeg("NetFare").InnerText)
            Next
    
    
    //ONWARD CONNECTION FLIGHTS
    
    FLTIntPriceReqConnectionPoInts = New List(Of FLTIntPriceReqConnectionSegment)
    
    
            For Each connection As XmlNode In OnwardConnectionLegs
                Dim flightDetailLeg As XmlNode = connection.FirstChild
    
                ObjFLTIntPriceReqConnectionSegment = New FLTIntPriceReqConnectionSegment
                FLTIntPriceReqFlightDetails = New FLTIntPriceReqFlightDetails
                FLTIntPriceReqFlightDetails.AdultFareID = 0
                FLTIntPriceReqFlightDetails.ChildFareID = 0
                FLTIntPriceReqFlightDetails.InfantFareID = 0
                FLTIntPriceReqFlightDetails.AirEquipType = ""
                FLTIntPriceReqFlightDetails.ArrivalAirportCode = flightDetailLeg("ArrivalAirportCode").InnerText
                FLTIntPriceReqFlightDetails.ArrivalDateTime = flightDetailLeg("ArrivalDateTime").InnerText
                FLTIntPriceReqFlightDetails.ArrivalTerminal = "Terminal 1"
                FLTIntPriceReqFlightDetails.AvailableSeats = flightDetailLeg("AvailableSeats").InnerText
                FLTIntPriceReqFlightDetails.BookingClass = flightDetailLeg("BookingClass").InnerText
                FLTIntPriceReqFlightDetails.CabinClass = flightDetailLeg("CabinClass").InnerText
                FLTIntPriceReqFlightDetails.ChangeOfGuage = False
                FLTIntPriceReqFlightDetails.DepartureAirportCode = flightDetailLeg("DepartureAirportCode").InnerText
                FLTIntPriceReqFlightDetails.DepartureDateTime = flightDetailLeg("DepartureDateTime").InnerText
                FLTIntPriceReqFlightDetails.DepartureTerminal = "Terminal 1"
                FLTIntPriceReqFlightDetails.FareBasisCode = flightDetailLeg("FareBasisCode").InnerText
                FLTIntPriceReqFlightDetails.FlightNo = flightDetailLeg("FlightNo").InnerText
                FLTIntPriceReqFlightDetails.FUID = 1
                FLTIntPriceReqFlightDetails.ValidatingAirLineCode = "6E"
                FLTIntPriceReqFlightDetails.MarketingAirLineCode = "6E"
                FLTIntPriceReqFlightDetails.OperatingAirLineCode = "6E"
                FLTIntPriceReqFlightDetails.Refundable = ""
                FLTIntPriceReqFlightDetails.RPH = 0
    
                ObjFLTIntPriceReqConnectionSegment.FLTIntPriceReqFlightDetails = FLTIntPriceReqFlightDetails
                FLTIntPriceReqConnectionPoInts.Add(ObjFLTIntPriceReqConnectionSegment)
            Next
    
            ObjFLTIntPriceReqFlightSegment.FLTIntPriceReqConnectionPoints = FLTIntPriceReqConnectionPoInts
            FLTIntPriceReqOnwardFlights.Add(ObjFLTIntPriceReqFlightSegment)
            ObjFLTIntPriceReqFlights.FLTIntPriceReqOnwardFlights = FLTIntPriceReqOnwardFlights
    
    
    //RETURN CONNECTION FLIGHTS
    FLTIntPriceReqConnectionPoInts = New List(Of FLTIntPriceReqConnectionSegment)
    
    
            For Each connection As XmlNode In returnConnectionLegs
                Dim flightDetailLeg As XmlNode = connection.FirstChild
    
                ObjFLTIntPriceReqConnectionSegment = New FLTIntPriceReqConnectionSegment
                FLTIntPriceReqFlightDetails = New FLTIntPriceReqFlightDetails
                FLTIntPriceReqFlightDetails.AdultFareID = 0
                FLTIntPriceReqFlightDetails.ChildFareID = 0
                FLTIntPriceReqFlightDetails.InfantFareID = 0
                FLTIntPriceReqFlightDetails.AirEquipType = ""
                FLTIntPriceReqFlightDetails.ArrivalAirportCode = flightDetailLeg("ArrivalAirportCode").InnerText
                FLTIntPriceReqFlightDetails.ArrivalDateTime = flightDetailLeg("ArrivalDateTime").InnerText
                FLTIntPriceReqFlightDetails.ArrivalTerminal = "Terminal 1"
                FLTIntPriceReqFlightDetails.AvailableSeats = flightDetailLeg("AvailableSeats").InnerText
                FLTIntPriceReqFlightDetails.BookingClass = flightDetailLeg("BookingClass").InnerText
                FLTIntPriceReqFlightDetails.CabinClass = flightDetailLeg("CabinClass").InnerText
                FLTIntPriceReqFlightDetails.ChangeOfGuage = False
                FLTIntPriceReqFlightDetails.DepartureAirportCode = flightDetailLeg("DepartureAirportCode").InnerText
                FLTIntPriceReqFlightDetails.DepartureDateTime = flightDetailLeg("DepartureDateTime").InnerText
                FLTIntPriceReqFlightDetails.DepartureTerminal = "Terminal 1"
                FLTIntPriceReqFlightDetails.FareBasisCode = flightDetailLeg("FareBasisCode").InnerText
                FLTIntPriceReqFlightDetails.FlightNo = flightDetailLeg("FlightNo").InnerText
                FLTIntPriceReqFlightDetails.FUID = 1
                FLTIntPriceReqFlightDetails.ValidatingAirLineCode = "6E"
                FLTIntPriceReqFlightDetails.MarketingAirLineCode = "6E"
                FLTIntPriceReqFlightDetails.OperatingAirLineCode = "6E"
                FLTIntPriceReqFlightDetails.Refundable = ""
                FLTIntPriceReqFlightDetails.RPH = 0
    
                ObjFLTIntPriceReqConnectionSegment.FLTIntPriceReqFlightDetails = FLTIntPriceReqFlightDetails
                FLTIntPriceReqConnectionPoInts.Add(ObjFLTIntPriceReqConnectionSegment)
            Next
    
    
            ObjFLTIntPriceReqFlightSegment.FLTIntPriceReqConnectionPoints = FLTIntPriceReqConnectionPoInts
            FLTIntPriceReqReturnFlights.Add(ObjFLTIntPriceReqFlightSegment)
            ObjFLTIntPriceReqFlights.FLTIntPriceReqReturnFlights = FLTIntPriceReqReturnFlights
    


    Using Split()

    2011-08-07


    Dim connectionString As String = "Persist Security Info=False;Integrated Security=FALSE;database=DBNAME;server=111.111.11.11;user id=sa;pwd=beta;"
    
    Dim splitComponents() As String = connectionString.Split(";")
    
    For Each item As String In splitComponents
    Dim splitAgain() As String = item.Split("=")
    Dim left As String = splitAgain(0)
    Dim right As String = splitAgain(1)
    If left = "database" Then
    sMainDB = right
    Exit For
    End If
    Next
    

    XSD to Class file generation

    2011-06-26

    Creating Class files from XSD using .net tool.

    @call "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
    
    xsd.exe YourXSDFile.xsd /YourClassFile /l:cs /n:NamespaceForTheClass
    
    pause
    



    l:cs- csharp class file you will get.
    l:vb - vb class file you will get.

    Save it as .bat & run.

    Excel Operations: Reading Data From Excel To DataTable & Generating Excel from DataTable

    2011-06-12

    Reading data from Excel to DataTable
    ----------------------------------------





    Public Function ConvertExcelToDT(ByVal sPath As String, ByVal sQuery As String) As DataTable
    
    ConvertExcelToDT = Nothing
    
    Dim ds As New DataSet
    
    Dim StrXLProvider As String = ""
    
    Dim OleAdpt As Data.OleDb.OleDbDataAdapter = Nothing
    
    Dim Connection As OleDb.OleDbConnection
    
    Try
    
    
    
    Connection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sPath + ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1""")
    
    OleAdpt = New Data.OleDb.OleDbDataAdapter(sQuery, Connection)
    
    OleAdpt.TableMappings.Add("Table", "Table")
    
    OleAdpt.Fill(ds)
    
    Connection.Close()
    
    resetcounter:
    
    For Each dr In ds.Tables(0).Rows
    
    If dr(0).ToString() = "" Then
    
    ds.Tables(0).Rows.Remove(dr)
    
    ds.Tables(0).AcceptChanges()
    
    GoTo resetcounter
    
    End If
    
    Next
    
    
    
    
    
    
    
    Catch ex As Exception
    
    ConvertExcelToDT = Nothing
    
    Me.Response.TransRemarks = ex.ToString()
    
    Me.Response.TransStatus = True
    
    Finally
    
    If Connection IsNot Nothing Then
    
    Connection.Close()
    
    Connection.Dispose()
    
    End If
    
    ConvertExcelToDT = ds.Tables(0)
    
    End Try
    
    
    
    End Function
    


    Reqs>>1. It should be Excel file
    2. AccessDatabaseEngine.exe should be installed to read data from Excel to DataTable other wise you will get The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
    3. No need of Excel to be installed in the hosting server

    Generating Excel from DataTable
    ----------------------------------

    Private Sub GenerateExcel(ByVal dtExcel As DataTable)
    
    Dim oAppln As Microsoft.Office.Interop.Excel.Application
    
    Dim oWorkBook As Microsoft.Office.Interop.Excel.Workbook
    
    Dim oWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
    
    Dim ColumnIndex As Int32 = 0
    
    Dim rowIndex As Int32 = 0
    
    Dim fileName As String = "JNTax" & DateTime.Now.ToString().Replace(":", "_").Replace("/", "-") + ".xls"
    
    Dim uploadingFilePath As String = Server.MapPath("AirlineRuleFiles")
    
    Try
    
    oAppln = New Microsoft.Office.Interop.Excel.Application()
    
    oWorkBook = DirectCast(oAppln.Workbooks.Add(True), Microsoft.Office.Interop.Excel.Workbook)
    
    'oWorkSheet = DirectCast(oWorkBook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing), Microsoft.Office.Interop.Excel.Worksheet)
    
    'oWorkSheet.Activate()
    
    oWorkSheet = oWorkBook.ActiveSheet()
    
    For Each col As DataColumn In dtExcel.Columns
    
    ColumnIndex += 1
    
    oWorkSheet.Cells(1, ColumnIndex) = col.ColumnName
    
    
    
    Next
    
    
    
    For Each row As DataRow In dtExcel.Rows
    
    rowIndex += 1
    
    ColumnIndex = 0
    
    For Each col As DataColumn In dtExcel.Columns
    
    ColumnIndex += 1
    
    oWorkSheet.Cells(rowIndex + 1, ColumnIndex) = row(col.ColumnName).ToString()
    
    Next
    
    
    
    Next
    
    If System.IO.Directory.Exists(uploadingFilePath) Then
    
    System.IO.Directory.Delete(uploadingFilePath, True)
    
    End If
    
    
    
    System.IO.Directory.CreateDirectory(uploadingFilePath)
    
    fileName = uploadingFilePath & fileName
    
    oWorkBook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Nothing, Nothing, False, False, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, False, False, Nothing, Nothing, Nothing)
    
    oWorkBook.Close(Nothing, Nothing, Nothing)
    
    oAppln.Quit()
    
    
    
    Response.ClearContent()
    
    Response.ContentType = "application/vnd.ms-excel"
    
    Response.WriteFile(fileName)
    
    Response.End()
    
    Catch ex As Exception
    
    
    
    End Try
    
    End Sub
    
    
    


    Reqs: 1. Excel should be installed if you are generating Excel using Excel Application class. Plus you need to set DCOM settings. I tried this one but faced issues so I won't recommend this method.

    There is another way to Generate Excel files without using Microsoft Excel Application class.


    Protected Sub GenerateExcelWithOutUsingExcelInterop(ByVal dtExcel As DataTable, ByVal fileName As String, ByVal sheetName As String)
    
    Dim stream As FileStream = Nothing
    
    Dim writer As ExcelWriter
    
    Dim uploadingFilePath As String = Server.MapPath("AirlineRuleFiles")
    
    Dim iheaderColumnsCount As Int16 = 0
    
    Dim iRow As Int16 = 0
    
    Dim iColumn As Int16 = 0
    
    Try
    
    
    
    If System.IO.Directory.Exists(uploadingFilePath) Then
    
    System.IO.Directory.Delete(uploadingFilePath, True)
    
    End If
    
    
    
    System.IO.Directory.CreateDirectory(uploadingFilePath)
    
    
    
    If Not System.IO.File.Exists(uploadingFilePath & fileName) Then
    
    stream = System.IO.File.Create(uploadingFilePath & fileName)
    
    End If
    
    
    
    writer = New ExcelWriter(stream)
    
    
    
    writer.BeginWrite()
    
    
    
    iRow = 0
    
    iColumn = 0
    
    For Each column As DataColumn In dtExcel.Columns
    
    writer.WriteCell(iRow, iColumn, column.ColumnName)
    
    iColumn += 1
    
    Next
    
    
    
    iRow = 1
    
    iColumn = 0
    
    For Each row As DataRow In dtExcel.Rows
    
    iColumn = 0
    
    For Each column As DataColumn In dtExcel.Columns
    
    writer.WriteCell(iRow, iColumn, row(column.ColumnName).ToString())
    
    iColumn += 1
    
    Next
    
    iRow += 1
    
    Next
    
    
    
    writer.EndWrite()
    
    stream.Close()
    
    
    
    Response.ClearContent()
    
    Response.ContentType = "application/vnd.ms-excel"
    
    Response.AppendHeader("Content-Disposition", "attachment; filename=" & sheetName & ".xls")
    
    Response.WriteFile(uploadingFilePath & fileName)
    
    Response.End()
    
    Catch ex As Exception
    
    Throw ex
    
    End Try
    
    
    
    End Sub
    

    Increment alphabet letter

    Dim startExcelColumn As String = "A"
    Dim lastExcelColumn As String = startExcelColumn
    
    For Each col As DataColumn In dtExcel.Columns
    If iCounter > 0 Then
    lastExcelColumn = Chr(Asc(lastExcelColumn) + 1)
    End If
    iCounter += 1
    Next
    
    
    oWorkSheet.Range(startExcelColumn & "1", lastExcelColumn & "1").Font.Bold = True
    


    Choosing a Collection Class

    2010-06-21


    I see quite often customer asking what is the right type of collection for specific purpose and performance overhead versus flexibility. This is again a passionate topic and it’s easy to get into debate with your colleagues especially during the peer code review processes.
    Choosing the right Collections class must be done carefully. Using the wrong collection can unnecessarily restrict how you use it.
    Consider the following questions:
    Do you need temporary storage?
    • If yes, consider Queue or Stack.
    • If no, consider the other collections.
    Do you need to access the elements in a certain order, such as first-in-first-out, last-in-first-out, or randomly?
    • The Queue offers first-in, first-out access.
    • The Stack offers last-in, first-out access.
    • The rest of the collections offer random access.
    Do you need to access each element by index?
    • ArrayList and StringCollection offer access to their elements by the zero-based index.
    • Hashtable, SortedList, ListDictionary, and StringDictionary offer access to their elements by the key of the element.
    • NameObjectCollectionBase and NameValueCollection offer access to their elements either by the zero-based index or by the key of the element.
    Will each element contain just one value or a key-singlevalue pair or a key-multiplevalues combination?
    • One value: Use any of the collections based on IList.
    • Key-singlevalue pair: Use any of the collections based on IDictionary.
    • Key-multiplevalues combination: Consider using or deriving from the NameValueCollection class in the Collections.Specialized namespace.
    Do you need to sort the elements differently from how they were entered?
    • Hashtable sorts the elements by the hash code of the key.
    • SortedList sorts the elements by the key, based on an IComparer implementation.
    • ArrayList provides a Sort method that takes an IComparer implementation as a parameter.
    Do you need fast searches and retrieval of information?
    • ListDictionary is faster than Hashtable for small collections of ten items or less.
    Do you need collections that accept only strings?
    • StringCollection (based on IList) and StringDictionary (based on IDictionary) are in the Collections.Specialized namespace.
    • Generic List

    What are the different types of assemblies? Satellite assembly?

    2008-10-06

    An assembly may be Public or Private. A public assembly is also called a Shared Assembly. An assembly is the basic building block in .NET. It is the compiled format of a class, that contains Metadata, Manisfest & Intermediate Language code. An assembly may be either Public or Private. A public assembly means the same as Shared Assembly. Private Assembly - This type of assembly is used by a single application. It is stored in the application's directory or the applications sub-directory. There is no version constraint in a private assembly. Shared Assembly or Public Assembly - A shared assembly has version constraint. It is stored in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by the .NET runtime. It is located at C:\Windows\Assembly OR C:\Winnt\Assembly. The shared assemblies may be used by many applications. To make an assembly a shared assembly, it has to be strongly named. In order to share an assembly with many applications, it must have a strong name. A Strong Name assembly is an assembly that has its own identity, through its version and uniqueness. In order to convert a private assembly to a shared assembly, i.e. to create a strongly named assembly, follow the steps below... 1) Create a strong key using the sn.exe tool. This is used to created a cryptographic key pair. The key pair that is generated by the Strong Name tool can be kept in a file or we can store it our your local machine's Crytographic Service Provider (CSP). For this, goto the .NET command interpreter, and type the following... sn -k C:\samplekey.snk This will create a strong key and save it to the location C:\samplekey.snk 2) If the key is stored in a file, just like we have done above, we use the attribute AssemblyKeyFileAttribute. This belongs to the namespace System.Reflection.AssemblyKeyFileAttribute. If the key was in the CSP, we would make use of System.Reflection.AssemblyKeyNameAttribute. Go to the assemblyinfo.vb file of your project. Open this file. Make the following changes in this file... We may write this in our code as well, like this... Imports System.Reflection Namespace StrongName Public class Sample End Class End Namespace 3) Build your project. Your assembly is now strongly named. Installing the Shared assembly in GAC... Go to .NET command interpreter, use the tool gacutil.exe Type the following... gacutil /i sampleclass.dll To uninstall it, use... gacutil /u sampleclass.dll. Visual Studio.NET provides a GUI tool for viewing all shared assemblies in the GAC. A Satellite Assembly - is an assembly that contains only resources, and no code. The resources are location specific. A satellite assembly is associated with a main assembly, the one that actually contains the code.