tag:blogger.com,1999:blog-28269753046043898862024-03-13T22:53:53.398-07:00Techie CocktailUnknownnoreply@blogger.comBlogger84125tag:blogger.com,1999:blog-2826975304604389886.post-65077101616236205422009-12-15T14:11:00.000-08:002009-12-15T14:34:22.042-08:00The server failed to load application '/LM/W3SVC/1/ROOT'. The error was 'Class not registered'.If these errors are occuring while running the .asp pages then below is the fix that will make things working for you.<br /><br /><strong>1. Error as displayed in the browser</strong>: The server failed to load application. Check Eventlog for more details.<br /><br /><strong>2. System log in the eventvwr - W3SVC</strong>: The server failed to load application '/LM/W3SVC/1/ROOT'. The error was 'Class not registered'.<br /><br /><blockquote><br /><strong>3. Event Viewer Application Log for MSDTC CLIENT</strong><br />Event Type: Error<br />Event Source: MSDTC Client<br />Event Category: (10)<br />Event ID: 4427<br />Description:<br />Failed to initialize the needed name objects. Error Specifics: d:\comxp_sp3\com\com1x\dtc\dtc\msdtcprx\src\dtcinit.cpp:215, Pid: 2536<br />No Callstack,<br /> CmdLine: C:\WINDOWS\System32\dllhost.exe /Processid:{xxxx}<br /></blockquote><br />4. <strong>Component Services -> COM+ in MMC</strong>, it will throw error.<br /><br />This means that COM+ on your system is corrupted and it is not able to communicate with msdtc. Also it is not able to get to the IIS Components/Packages in your COM+.<br /><br /><strong>Solution</strong><br />1. Fix MSDTC:<br /><br />a. Go to the command prompt<br />b. Change directory to C:\%windir%\system32<br />c. Type: msdtc -uninstall<br />d. Restart PC<br />e. Go to the command prompt<br />f. Change directory to C:\%windir%\system32<br />g. Type: msdtc -install<br /><br />2. After, msdtc is installed (Component Services -> COM+ in MMC will not throw any errors). Delete and re-register IIS Components/Packages in the COM+ by following the below steps:<br /><br />IIS related package in Component Services MMC<br />1. IIS In-Process Applications <br />2. IIS Out-of-Process Pooled Applications <br />3. IIS Utilities<br /><br /><strong>Steps</strong><br />a. In the Command Prompt, go to %windir%\system32\inetsrv folder <br />and run ><strong>rundll32 wamreg.dll, CreateIISPackage</strong> command<br /><br />b. run ><strong>regsvr32 asptxn.dll</strong><br /><br />c. Then reset IIS using <strong>iisreset</strong> command, then re-open Component Services MMC to verfiy the IIS Components/Packages are recreated.<br /><br />The above steps should make your .asp pages render properly!!!!!Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-2826975304604389886.post-85555961806279928452009-10-01T13:39:00.000-07:002009-10-01T13:43:17.905-07:00Detect Windows service status .NetGood article to detect the status of a windows service using a ServiceController class in .Net - <a href="http://www.blackwasp.co.uk/DetectServiceStatus.aspx" target="_blank">Detect Windows Service Status</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-66784635909099225612009-09-07T10:14:00.000-07:002009-09-07T10:29:34.728-07:00ASP.Net ConfigurationConfiguration settings has got its own importance in asp.net. It stores various settings for a lot of programming areas in asp.net. Some of them being, storing connection strings, page-level trace settings, httphandlers, httpmodules, authentication & authorization settings and a lot more.<br /><br />Its hard to remember all of these settings and their attributes. The below link is a good for reference link that covers most of the configuration settings:<br /><br /><a href="http://msdn.microsoft.com/en-us/library/b5ysx397(VS.71).aspx" href="_blank">http://msdn.microsoft.com/en-us/library/b5ysx397(VS.71).aspx</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-75420598568042711832009-08-22T00:15:00.000-07:002009-08-22T00:17:18.374-07:00Databinding ExpressionsDatabinding is one of the most important aspect in ASP.Net. Databinding, and one does not think about using <span style="font-weight:bold;">Eval</span> and <span style="font-weight:bold;">Bind</span> methods, not possible. Mostly you will find these methods used in .aspx page, and within <span style="font-weight:bold;"><%# and %></span> delimiters. <br /><br />Both retrieve values from the data-bound fields underneath the data-bound controls and renders them to the html page within your data-bound controls. In addition to just retrieving the value from database field, the Bind method can also submit your changes back into the database. This is the main difference between Eval & Bind methods.<br /><br />Eval is also called as read-only (select - database operation) method, and Bind is called as Read/Write (select, update, insert, delete - database operations) databinder method.<br /><br />Get more details at <a href="http://msdn.microsoft.com/en-us/library/ms178366.aspx">MSDN</a> explained very nicely.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-91163345153487240762009-08-11T23:47:00.000-07:002009-08-11T23:53:04.105-07:00Recover deleted emails in OutlookDo not worry if you have deleted your emails using Del or Shift+Del (permanent delete) in outlook because it provides an option to recover deleted emails.<br /><br />Go to Tools -> Recover Deleted Items which pops open a dialog where you can select the mails to recover.<br /><br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiP0Oajm14c17r_9VE1OIr986wbjuGPQiFtCD77jabKSFEC7uMfUoVU0xssZhOrr1TZ2wD_RkcwHHxkiqcwXF70u_NM61i84SMxtYsnYJxd7KHUebU97i6dOw8RHXKSsxqhu9HjSFSG8tqH/s1600-h/recover.jpg"><img style="cursor:pointer; cursor:hand;width: 320px; height: 200px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiP0Oajm14c17r_9VE1OIr986wbjuGPQiFtCD77jabKSFEC7uMfUoVU0xssZhOrr1TZ2wD_RkcwHHxkiqcwXF70u_NM61i84SMxtYsnYJxd7KHUebU97i6dOw8RHXKSsxqhu9HjSFSG8tqH/s320/recover.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5368966609469771378" /></a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-25878320794517920402009-08-07T14:19:00.000-07:002009-08-07T14:21:27.212-07:00Optimize SQL Using SET ROWCOUNT<strong>SET ROWCOUNT</strong> causes SQL Server to stop processing the query after the specified number of rows are returned.<br /><br />Once the ROWCOUNT is set then the following queries would return those many number of rows in the resultset irrespective of any filtering or conditions applied.<br /><br />To turn off this option, set the ROWCOUNT to 0. This command can be executed by any <br />users. The user need not have any special permissions to execute this command.<br /><blockquote><br />Syntax:<br />SET ROWCOUNT <number> | <@number_var><br /></blockquote><br />It is the best way to optimize a query, if we are aware of how many records we would <br />need at a time. For example, if you are performing custom paging for GridView in <br />asp.net 2.0, then you can set the query to return only the required number of rows as set in the PageSize property of the GridView.<br /><br />Visit MSDN for more details with examples: <a href="http://msdn.microsoft.com/en-us/library/ms188774.aspx">MSDN</a>Unknownnoreply@blogger.com5tag:blogger.com,1999:blog-2826975304604389886.post-77673732265293156092009-08-07T12:36:00.001-07:002009-08-07T12:37:39.947-07:00Introduction to Microsoft Office 2010Chris Bryant introduces the new Microsoft Office 2010. Checkout the video for more details.<br /><br /><object width="480" height="295"><param name="movie" value="http://www.youtube.com/v/45HJpjdUzpY&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/45HJpjdUzpY&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="295"></embed></object>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-2826975304604389886.post-63533977882527237592009-07-31T09:55:00.000-07:002009-08-04T07:27:12.140-07:00News - 07.31.2009Look out for any USA jobs by visiting our job site at - <a href="http://techiecocktail.jobamatic.com/a/jobs/find-jobs">USA Jobs</a>.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-37074923989589559452009-07-24T18:20:00.000-07:002009-07-24T18:22:37.042-07:00Displaying culture specific date formatsDifferent countries use different date formats. Hard-coding different date formats in a multi-lingual application is definitely a bad choice. To display the date in the date format as used for a country, .net has <strong>ToShortDateString()</strong> function. <br /><br />ToShortDateString() is culture-sensitive and outputs the date which is specific to the current culture set. Below example shows its use.<br /><blockquote><br />class Program<br />{<br /> static void Main(string[] args)<br /> {<br /> //get the current culture and display its date format.<br /> DateTime _date = DateTime.Now;<br /> CultureInfo _currentCulture = Thread.CurrentThread.CurrentCulture;<br /> Console.WriteLine("Current Culture: {0}: ", _currentCulture.Name);<br /> Console.WriteLine(_date.ToShortDateString());<br /><br /> //set the current culture to french & display the french date format<br /> Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");<br /> Console.WriteLine("French Culture: {0}", _date.ToShortDateString());<br /><br /> //set the current culture to italian & display the italian date format<br /> Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");<br /> Console.WriteLine("Italian Culture: {0}", _date.ToShortDateString());<br /><br /> //set the current culture to german & display the german date format<br /> Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");<br /> Console.WriteLine("German Culture: {0}", _date.ToShortDateString());<br /><br /> //set the current culture to spanish and display the spanish date format<br /> Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");<br /> Console.WriteLine("Spanish Culture: {0}", _date.ToShortDateString());<br /><br /> //set back to the original date format<br /> Thread.CurrentThread.CurrentCulture = _currentCulture;<br /> Console.WriteLine("Back to original Culture: {0}", _date.ToShortDateString());<br /><br /> Console.Read();<br /> }<br />}<br /></blockquote><br /><strong>Get list of Cultures</strong><br /><br />If you are not aware of the culture names then you can use the following function to get the complete list of available cultures. You can use CurrentTypes enum that defines the types of culture lists that can be retrieved. The below example gets the list of all the cultures that ship with .NET Framework, including neutral and specific cultures, cultures installed in Windows OS and custom cultures created by the user.<br /><br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKS6EFx5vCJ_xhlVT5c21Nhyphenhyphen_GlWo_IehGzxXN915M-d-uElb-w4mDJgIVxrmRVIvPdlB2c8bKrT3zeZ5uNhQoXS7YnQPY6NqMi1s3aIUE9t9l3i36H4dS4oycIvgpMuP9m_luSGfUr-b7/s1600-h/getallcultures.jpg"><img style="cursor:pointer; cursor:hand;width: 320px; height: 256px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKS6EFx5vCJ_xhlVT5c21Nhyphenhyphen_GlWo_IehGzxXN915M-d-uElb-w4mDJgIVxrmRVIvPdlB2c8bKrT3zeZ5uNhQoXS7YnQPY6NqMi1s3aIUE9t9l3i36H4dS4oycIvgpMuP9m_luSGfUr-b7/s320/getallcultures.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5362201832596821458" /></a><br /><blockquote><br />static void GetAllCultures()<br />{<br /> string specificCultureName = "";<br /> CultureInfo[] arrCultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures);<br /><br /> foreach (CultureInfo ci in arrCultureInfo)<br /> {<br /> try<br /> {<br /> specificCultureName = CultureInfo.CreateSpecificCulture(ci.Name).Name;<br /> }<br /> catch { }<br /><br /> Console.WriteLine(ci.Name + ": " + specificCultureName + ": " + ci.EnglishName);<br /> specificCultureName = "----";<br /> }<br /> Console.Read(); <br />}<br /></blockquote>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-60195981431975306432009-07-22T15:18:00.000-07:002009-07-22T15:28:40.830-07:00WCF for beginnersThis screencast shows how to build your first WCF service using Visual Studio 2008.<br /><br /><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/JlyND7b2-YA&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/JlyND7b2-YA&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object><br /><br />Aaron Skonnard has nicely demonstrated the implementation of WCF service followed by testing and hosting the service.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-18719586097378516072009-07-20T20:50:00.000-07:002009-07-20T20:52:55.319-07:00News - 07.20.2009Users please bear with us as we are in process of updating the design. You may see some breaks in the site for a day or two. <br /><br />Sorry for the inconvenience caused due to this.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-86071866264205501792009-07-18T10:14:00.000-07:002009-07-20T15:46:07.238-07:00News - 07.18.2009We are planning to go for a new template design, as we are experiencing some limitation with this design. Our focus is to use a design that makes it easy for our users to browse across different articles & sections.<br /><br />We would also like to take this opportunity to get the feedback from you on how we are doing. Please write us in at techiecocktail@yahoo.com.<br /><br />Please feel free to also let us know what else you would like to see in our site, what other topics you would like us to write and any other comments.<br /><br />We would also like to invite people to help us by writing articles for our site or help us in any ways. Our focus is to provide useful technical content, that gives complete information to our users on any technology, tools, tips-n-tricks, resources or any new upcoming technical news articles from any domain like telecommunication, software, finance, real-estate.<br /><br />If you would like to help us, please mail us your information with email address and/or contact number. We will reach you for more details. After we have received 5 useful and complete articles from you, we will send you a $10 (USA Dollars) worth gift card of your choice for your participation.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-61905605501526209402009-07-17T17:55:00.000-07:002009-07-20T15:46:07.249-07:00Windows Run Commands - ShortcutsSome of the useful Run Commands shortcuts for Windows for some of the common tasks that we perform everyday. These are very useful if you get used to them as it saves lot of navigational time.<br /><br />Let us know if you know about any other shortcuts and we will add them to this list.<br /><br /><strong>appwiz.cpl</strong>: <br /> Add/Remove Programs Wizard.<br /><br /><strong>control</strong>:<br /> Access Control Panel<br /><br /><strong>cmd</strong>:<br /> Open the Command Prompt Window.<br /><br /><strong>calc</strong>:<br /> Calculator<br /><br /><strong>compmgmt.msc</strong>:<br /> Open the Computer Management Window.<br /><br /><strong>dcomcnfg</strong>:<br /> Open Component Services Window.<br /><br /><strong>certmgr.msc</strong>:<br /> Open the Certificate Manager Window.<br /><br /><strong>mstsc</strong>:<br /> Open the Remote Desktop session window.<br /><br /><strong>desk.cpl</strong>:<br /> View systems display properties.<br /><br /><strong>eventvwr</strong>:<br /> Opens the Event Viewer window<br /><br /><strong>regedit</strong>:<br /> Opens the registry.<br /><br /><strong>fonts</strong>:<br /> Opens up the fonts folder in the Windows Explorer window displaying the <br />available fonts.<br /><br /><strong>inetcpl.cpl</strong>:<br /> Opens the internet properties windows.<br /><br /><strong>control keyboard</strong>:<br /> Opens the keyboard properties window.<br /><br /><strong>main.cpl</strong>:<br /> Opens the mouse properties window.<br /><br /><strong>osk</strong>:<br /> Opens the onscreen keyboard. This could be very useful if you keyboard is not <br />connected to your system.<br /><br /><strong>control printers</strong>:<br /> Opens the printers folder in the control panel.<br /><br /><strong>control admintools</strong>:<br /> Opens the Administrative Tools folder in the control panel.<br /><br /><strong>control folders</strong>:<br /> Opens the Folder Options window.<br /><br /><strong>control color</strong>:<br /> Opens the Appearance Property dialog window.<br /><br /><strong>control schedtasks</strong>:<br /> Opens the scheduled task in the control panel.<br /><br /><strong>perfmon</strong>:<br /> Opens the performance counters window.<br /><br /><strong>cleanmgr</strong>:<br /> Opens the disk cleanup utility.<br /><br /><strong>devmgmt.msc</strong>:<br /> Opens the Device Manager window.<br /><br /><strong>dxdiag</strong>:<br /> Opens the DirectX Diagnostic Tool.<br /><br /><strong>hdwwiz.cpl</strong>:<br /> Add New Hardware Wizard.<br /><br /><strong>gpedit.msc</strong>:<br /> Opens the Local Group Policy Editor window.<br /><br /><strong>lusrmgr.msc</strong>:<br /> Opens the Local Users & Groups window.<br /><br /><strong>ncpa.cpl</strong>:<br /> Opens the Network Connections in the control panel.<br /><br /><strong>firewall.cpl</strong>:<br /> Opens the Firewall Settings window.<br /><br /><strong>sqlwb</strong>:<br /> Opens the SQL Server.<br /><br /><strong>services.msc</strong>:<br /> Opens the Services window.<br /><br /><strong>winword</strong>:<br /> Opens the MS word application.<br /><br /><strong>excel</strong>:<br /> Opens the excel application.<br /><br /><strong>notepad</strong>:<br /> Opens the notepad application.<br /><br /><strong>mspaint</strong>:<br /> Opens the MS Paint application.<br /><br /><strong>wordpad</strong>:<br /> Opens Wordpad application.<br /><br /><strong>powerpnt</strong>:<br /> Opens Microsoft Powerpoint application.<br /><br /><strong>explorer</strong>:<br /> Opens Windows Explorer.<br /><br /><strong>iexplore</strong>:<br /> Opens Internet Explorer Browser.<br /><br /><strong>inetmgr</strong>:<br /> Open Internet information services window.<br /><br /><strong>wab</strong>:<br /> Opens the windows address book showing contact files for each user.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-31795410963140655732009-07-10T06:13:00.000-07:002009-07-20T15:46:07.258-07:00Client-Side State Management in Asp.NetASP.Net is a stateless connection. The pages gets recreated every time the page is posted back to the server. In order to maintain the changes done by the user, asp.net has different state management techniques.<br /><br />ASP.Net supports Client-side and Server-side State Management options as listed below. In this article we will see client-side management techniques.<br /><br /><span style="font-weight: bold;">Client-side State Management</span><br /><br />In this approach, the state information is stored on the client's computer/browser in the form of a URL, Cookies or as Hidden Fields in the webpage. Client side approach is scalable as it stores data on multiple servers i.e. each users information on their own system. There is no need for the server to remember their individual preferences. But on the other hand, client-side approach can create performance bottle necks if large data is stored, as the data would travel between client and server during postbacks.<br /><br />Lets see these techniques in details with examples.<br /><br />a. <span style="font-weight:bold;">QueryString</span>: With this option, you can pass values from one page to another as query strings, appended to the end of the page's url. Use this option if you are not passing any important values like email id, or any other parameter value as it is visible to the user.<br /><br /><strong>Building a QueryString</strong><br />The values in the query string passed as key/value pairs seperated by an '&' (ampersand). You can use Server.Transfer or Response.Write method to redirect to the other page by concatenating the parameters as below.<br /><blockquote><br />http://www.test.com/test.aspx?day=14&month=07&year=2010<br /></blockquote><br /><br /><strong>Getting values from the querystring</strong><br />Below example shows how to get the day, month & year values from the querystring. You can get the querystring value by passing in the name of the querystring or by index to the Request.QueryString object.<br /><blockquote><br />Request.QueryString["day"] or Request.QueryString[0]<br />Request.QueryString["month"] or Request.QueryString[1]<br />Request.QueryString["year"] or Request.QueryString[2]<br /></blockquote><br /><br />b. <span style="font-weight:bold;">Cookies</span>: Cookies store the information on the users system. Information like login information, user preferences are generally stored in cookies. Cookies can be accessed across multiple pages. This option is not used to store large values as the information travels back and forth between client & server.<br /><br /><strong>Store the cookies values in Form1.aspx and redirect to Form2.aspx</strong><br /><blockquote><br />Response.Cookies["firstname"].Value = "John";<br />Response.Cookies["lastname"].Value = "Deller";<br /><br />Server.Transfer("~/form2.aspx");<br /></blockquote><br /><br /><strong>Retrive cookies value in Form2.aspx page using a label control</strong><br /><blockquote><br />lblFinal.Text = Request.Cookies["firstname"].Value + " " + Request.Cookies["lastname"].Value;<br /></blockquote><br /><br />c. <span style="font-weight:bold;">Hidden Fields</span>: Hidden Fields are stored at the client's side, as HTML on the web page but they are not visible to the user in the page's output on the browser.<br /><br />It can be viewed by the user by opening the page source hence not used to store important data. As hidden fields also travels back and forth on each requests, it is recommended not to store large data in the hidden fields to avoid performance issues. It can be used to store data related to the user & their preferences.<br /><br /><strong>Store values in hidden field</strong><br />Insert a placeholder tag which will be replaced by the one that you pass using the code as below:<br /><br /><strong>Aspx page</strong>: <br /><asp:PlaceHolder ID="plHolder" runat="server"></asp:PlaceHolder><br /><br /><strong>Code</strong>:<br /><blockquote><br />HtmlInputHidden _htmlInputHidden = new HtmlInputHidden();<br />_htmlInputHidden.ID = "promotion";<br />_htmlInputHidden.Value = "50% discount on men's wear";<br /><br />plHolder.Controls.Add(_htmlInputHidden);<br /></blockquote><br /><br /><strong>Retrieving the value from hidden field</strong><br /><blockquote><br />String strHiddenValue = ((HtmlInputHidden)plHolder.FindControl("promotion")).Value;<br /></blockquote><br /><br />d. <span style="font-weight:bold;">View State</span>: View State are also stored as HTML on the web page, similar to hidden fields. The data stored in the view state is specific to that page, it cannot be passed to the other pages. <br /><br />Data can be retained in the view state in between post backs. Most of the server controls in asp.net use view state to retain the data entered by the user during post backs. Custom values can be stored in the view state object.<br /><br />Again, as this is passed between client and server during post backs, store small amount of data to avoid performance bottlenecks.<br /><br /><strong>Storing value in view state</strong>: ViewState["test"] = "This is a test string";<br /><br /><strong>Retrieving value from view state</strong>: String strViewState = ViewState["test"];<br /><br />e. <span style="font-weight:bold;">Control State</span>: Control state is like View State but reserved for the custom control you develop. So if you are building your own custom control, its better to use Control State so the users using your control do not break your control by disabling View State.<br /><br />Refer: http://www.pluralsight.com/community/blogs/fritz/archive/2004/07/01/472.aspx for more details & example.<br /><br /><strong>References</strong><br />http://msdn.microsoft.com/en-us/library/75x4ha6s.aspxUnknownnoreply@blogger.com1tag:blogger.com,1999:blog-2826975304604389886.post-38723431026370726282009-07-09T12:05:00.000-07:002009-07-20T15:46:07.277-07:00Generate random numbers.Net provides an object called 'Random' to generate random numbers. It is contained in System namespace.<br /><br />Using the Random object we can generate random integers, bytes and doubles. The Random object contains 3 methods called <strong>Next</strong>, <strong>NextBytes</strong> and <strong>NextDouble</strong> for this purpose. To use the object create an instance of the Random class and call its methods.<br /><blockquote><br />Random ranGen = new Random();<br /></blockquote><br /><br /><strong>Methods</strong><br /><br />a. Next: <br /> Takes an integer number as the maximum number and returns a random non-negative number less than the maximum number supplied.<br /><blockquote><br />int number = ranGen.Next(10);<br /></blockquote><br />b. NextBytes:<br /> Takes the buffer of byte[] and fills the buffer elements with random byte numbers.<br /><blockquote><br />byte[] buffer = new byte[10];<br />ranGen.NextBytes(buffer);<br /><br />foreach (byte bte in buffer)<br />{<br /> Console.WriteLine(bte.ToString());<br />}<br /></blockquote><br /><br />c. NextDouble:<br /> Returns a random double between 0.0 and 1.0 value.<br /><blockquote><br />double number = ranGen.NextDouble();<br /></blockquote>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-67059565797900948692009-06-21T21:57:00.000-07:002009-07-20T15:46:07.286-07:00Intellisense support for XML and JavascriptVisual Studio 2008 has new set of supported tools and resources to offer. One of it is intellisense support which is really useful to have at the time of writing the code. It helps developers with a quick in time reference support to the available members & methods within the objects thereby saving a lot of time.<br /><br />This article is intended to create an awareness of these available tools and resources in Visual Studio 2008. Rest assured, it is very easy to find help of these resources on the internet. Just bing it.<br /><br />a. <strong>XML Intellisense</strong>:<br /> XML intellisense support is really useful to the developers as it provides the elements or the child elements details for a node selected. This prevents them to remember or refer to the xml structure in between coding. <br /><br />The tool support provided by microsoft is '<strong>XML to Schema interface Wizard</strong>'. It is very easy to use. Just download and install the tool from microsoft site. <br /><br />It creates a new template in VS 2008 called 'XML to Schema'. Select your xml document whose schema you want to create. Boom. You will see the XSD file created in your project and also while coding, intellisense support is provided.<br /><br />b. <strong>Javascript Intellisense</strong>:<br /> Javascript intellisense support is another thing that is liked by the developers. Some .net developers find difficult coding in java script as there was not much support about the language methods and classes earlier. <br /><br />With the help of this, developers now get the javascript intellisense while coding the .aspx page (html) and get the handy information of various available members & methods.<br /><br />Infact not other than this, VS 2008 also supports javascript debugging. Bing it.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-24055288540154759472009-06-13T12:32:00.000-07:002009-07-20T15:46:07.295-07:00Remove unused using statementsIn C#, using statements are used to reference namespaces. We tend leave unused spaces as is many times without bothering if any extra using statements are left out. But we do not need to bother at all now because visual studio 2008 has given us one handy option/tool integrated within the VS IDE in the source code unit.<br /><br /><span style="font-weight:bold;">Right click anywhere in the source code unit -> Organize Usings -> Remove Unused Usings</span>. <br /><br />This removes the unused usings statements, leaving behind the usings references of only those namespaces whose classes are being used in your code.<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh599X6I-Drt7RrRIC__HDKGK_hvvTBf0HkysxTrmOi2Xz7XK5zMTn3VaSPXL1M2rhafM28y6W2MIBcgrCoWew-vYEBI7byud0v8JSmG7mnA15J429vhyphenhyphenQIF6OAAJb_Iue3HpBfxvOop5dE/s1600-h/screenshot.jpg"><img style="cursor:pointer; cursor:hand;width: 320px; height: 178px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh599X6I-Drt7RrRIC__HDKGK_hvvTBf0HkysxTrmOi2Xz7XK5zMTn3VaSPXL1M2rhafM28y6W2MIBcgrCoWew-vYEBI7byud0v8JSmG7mnA15J429vhyphenhyphenQIF6OAAJb_Iue3HpBfxvOop5dE/s320/screenshot.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5346897710487287154" /></a><br /><br />As seen in the above figure, you can also sort Usings or Remove and Sort both. This option is available both for windows and web projects.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-88257466989058454742009-06-10T17:17:00.000-07:002009-07-20T15:46:07.314-07:00Insert and Delete sql table records - LINQ to SQLIn the <a href="http://techiecocktail.blogspot.com/2009/05/linq-to-sql-overview.html">LINQ to SQL Overview</a>, we saw the internals of LINQ to SQL with a simple example showing how to retrieve data from SQL. In this article we will see how to insert and delete records in a SQL table using LINQ to SQL.<br /><br />Lets take the same example as in the Overview article and insert to and delete records from the Countries table.<br /><br /><strong>Insert Records</strong><br /><br />To insert records to the table, the LINQ provides two methods - <br /><strong>InsertOnSubmit()</strong> - Used insert single record to the database.<br /><strong>InsertAllOnSubmit()</strong> - Used to insert multiple records to the database. <br /><br />These inserts are actually commited to the database when <strong>SubmitChanges()</strong> method of the DataContext is called. Lets insert Australia, Germany & Russia to the Countries table.<br /><br /><strong>Note</strong>: The insert, delete and update operations won't work if the table does not have a primary key set.<br /><br /><div class="postCode"><br />public static void InsertCountries()<br />{<br /> //Create the Countries DataContext object.<br /> CountriesDataContext _countriesDataContext = new CountriesDataContext();<br /><br /> //Create the List of type Country.<br /> //This list would contain the new countries that we will insert in the database.<br /> List<Country> lstCountry = new List<Country>();<br /><br /> //New country objects<br /> Country _1stCountry = new Country();<br /> _1stCountry.CountryId = 7;<br /> _1stCountry.CountryName = "Russia";<br /> lstCountry.Add(_1stCountry);<br /><br /> Country _2ndCountry = new Country();<br /> _2ndCountry.CountryId = 8;<br /> _2ndCountry.CountryName = "Germany";<br /> lstCountry.Add(_2ndCountry);<br /><br /> Country _3rdCountry = new Country();<br /> _3rdCountry.CountryId = 9;<br /> _3rdCountry.CountryName = "Australia";<br /> lstCountry.Add(_3rdCountry);<br /><br /> //Use InsertAllOnSubmit method to insert the new country list.<br /> _countriesDataContext.Countries.InsertAllOnSubmit(lstCountry);<br /><br /> //Commit to the database.<br /> _countriesDataContext.SubmitChanges();<br />}<br /></div><br /><br /><strong>Delete Records</strong><br /><br />To delete records, we use <strong>DeleteOnSubmit()</strong> or <strong>DeleteAllOnSubmit()</strong> methods followed by <strong>SubmitChanges()</strong> method of the DataContext. <br /><br />Lets delete few countries from the Country table. Lets say, we want to delete all the countries with CountryId > 5.<br /><br /><div class="postCode"><br />public static void DeleteCountries()<br />{<br /> CountriesDataContext _countriesDataContext = new CountriesDataContext();<br /><br /> var cntries = from c in _countriesDataContext.Countries<br /> where c.CountryId > 5<br /> select c;<br /><br /> _countriesDataContext.Countries.DeleteAllOnSubmit(cntries);<br /> _countriesDataContext.SubmitChanges();<br />}<br /></div><br /><br />There are many insert, delete or update scenarios that people can encounter. MSDN provides good reference - <a href="http://msdn.microsoft.com/en-us/vbasic/bb688085.aspx" target="_blank">LINQ to SQL Samples</a> covering most of the scenarios.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-9805715402085214162009-06-04T01:09:00.000-07:002009-07-20T15:46:07.326-07:00XML Documentation in .Net<strong>Introduction</strong><br /><br />Code documentation is important to be followed as the standard practise. Obviously its not an interesting job to the code developers, for many reasons and also because of laziness issues. It again depends on the importance of documentation. Lets forget these documentation talks. But bottomline, it is really important for future reference purpose. You will believe one day and some of you already believe that.<br /><br />Most of the devlepers follow the basic comenting. But if you really want to follow the authentic professional method, .net has it all. The line or block of code is generally commented using //(double forward slash - single line), or /* */ (within slash, asterik block - multiple lines). <br /><br />But if you want to distribute your code or class libraries to your clients, its very helpful if you submit thorough documentation file along with it for reference purpose.<br /><br /><strong>XML comment tags used for documentation</strong><br /><br />Lets get into the actuals now. If you type /// (3 slashes) in the source code unit, you will see an XML block that gets auto-generated for you. This is the comment block in xml format. The basic comment tags that show up depends upon where you have put the slashes. If it is above the function block, you will see the below segment,<br /><br /><strong>Sample with default tags</strong><br /><blockquote><br />/// <summary><br />/// <br />/// </summary><br />/// <param name="number1"></param><br />/// <param name="number2"></param><br />/// <returns></returns><br />static int addTwoNumbers(int number1, int number2)<br />{<br />}<br /></blockquote><br />As seen above, we have <summary>, <param>, <returns> tags added automatically. The <summary> tag is used to provide the summary details on what the method does. The <param> tags are included, to write details on the parameters being passed to the method. And the <returns> is included for details on the return type and/or value from the method.<br /><br />Note, these xml tags must conform the xml rules otherwise you will get warnings and also you final xml documentation file would not contain the errorneous tags until you fix them.<br /><br />Lets see other commonly used xml tags available for comments as below:<br /><br />1. <remarks> - Used to provide detailed information about a type or member.<br />2. <paramref> - Used to create a reference to a parameter.<br />3. <see cref="" /> - Used to create a reference to any type or a memeber.<br />4. <exception cref="" /> - Used to create details on exceptions.<br />5. <c> or <code> - <c> is Used to demonstrate a <br />small code segment whereas <code> tag is used to demonstrate multi-lines code segment.<br />6. <example> - used to demonstrate code examples. Usually the <c> and <code> tags are contained withing <example> tag.<br /><br />Once these tags are in place in the code, follow these 2 steps and C# compiler will generate the XML Documentation file at the specified location.<br /><br />a. Check the XML Documentation file checkbox and specify the file location, in the Build tab of the project's properties.<br />b. Build the application.<br /><br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgKGr8fr-ax07Wgrf5HoLgGXLEA4A4HdoZC7MF-SgoJr_8AWWJMNl8NoiiJBHi04AZc12zTPkiNEqWY93wOWhpQ4Hc8qw-Rogww6pQhkvx3yl3dc-1HTC2tbp59DJbEnBtiJv6gjushfT9/s1600-h/projectproperty.jpg"><img style="cursor:pointer; cursor:hand;width: 320px; height: 224px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgKGr8fr-ax07Wgrf5HoLgGXLEA4A4HdoZC7MF-SgoJr_8AWWJMNl8NoiiJBHi04AZc12zTPkiNEqWY93wOWhpQ4Hc8qw-Rogww6pQhkvx3yl3dc-1HTC2tbp59DJbEnBtiJv6gjushfT9/s320/projectproperty.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5343386588632858450" /></a><br /><br />Lets see a complete code source example with some of the comments tags as mentioned above. After the source code is the XML Documentation file generated.<br /><br /><strong>Source Code with XML Comments as Code documentation</strong><br /><blockquote><br />using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br /><br />namespace xmlDocumentation<br />{<br /> class Program<br /> {<br /> /// <summary><br /> /// This is the entry point method of this project.<br /> /// </summary><br /> /// <param name="args"></param><br /> static void Main(string[] args)<br /> {<br /> int number1 = 1;<br /> int number2 = 2;<br /> addTwoNumbers(number1, number2);<br /> }<br /> <br /> /// <summary><br /> /// <br /> /// </summary><br /> /// <param name="number1"></param><br /> /// <param name="number2"></param><br /> /// <returns><see cref="int" /></returns><br /> /// <paramref name="number1">Number 1 is the big number</paramref><br /> /// <remarks></remarks><br /> /// <example><br /> /// <c>Result = number1+number2;</c><br /> /// </example><br /> static int addTwoNumbers(int number1, int number2)<br /> {<br /> return number1 + number2;<br /> }<br /> }<br />}<br /></blockquote><br /><strong>XMLDocumentation.xml file</strong><br /><blockquote><br /><?xml version="1.0"?><br /><doc><br /> <assembly><br /> <name>xmlDocumentation</name><br /> </assembly><br /> <members><br /> <member name="M:xmlDocumentation.Program.Main(System.String[])"><br /> <summary><br /> This is the entry point method of this project.<br /> </summary><br /> <param name="args"></param><br /> </member><br /> <member name="M:xmlDocumentation.Program.addTwoNumbers(System.Int32,System.Int32)"><br /> <summary><br /> <br /> </summary><br /> <param name="number1"></param><br /> <param name="number2"></param><br /> <returns><see cref="T:System.Int32"/></returns><br /> <paramref name="number1">Number 1 is the big number</paramref><br /> <remarks>This method will add the two numbers being passed as the parameters and returuns the sum of two numbers as the result.</remarks><br /> <example><br /> <c>Result = number1+number2;</c><br /> </example><br /> </member><br /> </members><br /></doc><br /></blockquote><br /><strong>Representation</strong><br /><br />This article is mainly focussed on getting you familiarized with the available xml tags that can be used to document your code and generate xml documentation file.<br /><br />Once your xml documentation .xml file is ready, you need to present it in a common man readable format. Some of the available tools that can be used to convert the xml document are stated below. We suggest you to explore them and use based on your liking and requirements.<br /><br />a. <strong>XSL</strong> - <br /> You can develop your own XSL stylesheet to decorate the above .xml comment file.<br /><br />b. <strong>NDoc</strong> - <br /> This is an extensible code documentation generation tool for .NET Developers. It is completely free to download and use. It converts the .xml file as above and coverts it into .chm file. It is very easy to use. You can find the download link at: http://sourceforge.net/projects/ndoc/<br /><br />c. <strong>Sandcastle</strong> - <br /> Sandcastle is provided by Microsoft. It produces accurate, MSDN Style, comprehensive documentation and is also easy to use. This tool is available for download at: http://www.microsoft.com/downloads/details.aspx?FamilyId=E82EA71D-DA89-42EE-A715-696E3A4873B2&displaylang=en<br /><br />d. <strong>DOxygen</strong> - <br /> Another souce code documentation generator tool. It is developed under Linux and Mac OS x but highly portable. It supports many output format but the popular one is HTML that is widely accepted. This tool is also easy and available for free at: http://www.stack.nl/~dimitri/doxygen/download.html#latestsrc<br /><br />These are some of the common available options. There may be other tools available or may come in future.<br /><br />Hope you start documenting your code after knowing the available easy and neat options to generate professional documentation. Keep patience and have fun.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-38911299340224629722009-05-21T20:53:00.000-07:002009-07-20T15:46:07.351-07:00Store and Retrieve Image from SQL Database using ASP.Net<strong>Introduction</strong><br /><br />In Sql Server 2005 we have Image datatype to store images. Let's see a simple example on how to store an image to a Sql database table. Then we will see how to retrieve the stored image from the sql table and display it in the Image Server Control using ASP.Net.<br /><br />This example uses VS 2008 for Asp.Net and Sql Server 2005. Below figure shows the simple web interface with 2 sections. The first section allows user to browse an image file (.jpg) using the FileUpload Server control and then using the button submits/saves the image to the Sql database. The second part allows the user to retrieve & display the latest image from the Sql table to the Image Server Control.<br /><br /><strong>Web Interface</strong><br /><br />For the simplicity the web interface is kept simple here.<br /><br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhOW89SePcYjUIxqFieyg8o_ZdkY_AZcPjsOp0BZJQVAQ-2G8zz8B_nKSdbxdh-I2vHNgnWWK_z7siAgfKjPbtz52_lazwWULsWUoC_faZ-pGU7hhJJ_1B-EUPkxlKSF6kSDK7uEGGBMmXM/s1600-h/fig1.jpg"><img style="cursor:pointer; cursor:hand;width: 320px; height: 262px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhOW89SePcYjUIxqFieyg8o_ZdkY_AZcPjsOp0BZJQVAQ-2G8zz8B_nKSdbxdh-I2vHNgnWWK_z7siAgfKjPbtz52_lazwWULsWUoC_faZ-pGU7hhJJ_1B-EUPkxlKSF6kSDK7uEGGBMmXM/s320/fig1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5338492325241791234" /></a><br /><br />As seen in the above page, there is an alternate text displayed in the image control when it does not refer to any image.<br /><br />Below is the .aspx page code for reference:<br /><br /><blockquote><br /> <form id="form1" runat="server"><br /> <div><br /> <p><b><asp:Literal ID="lit_storeImage" runat="server">Store Image to DB</asp:Literal></b></p><br /> <asp:Label ID="lbl_SelectFile" runat="server" Text="Select an image file to upload: "></asp:Label><br /> <asp:FileUpload ID="FileUpload_images" runat="server" /><br /> <br /><br /> <br /><br /> <asp:Button ID="btn_storeImageInDB" runat="server" <br /> onclick="btn_storeImageInDB_Click" Text="Store Image in DB" /><br /> </div><br /> <hr /><br /> <div><br /> <p><b><asp:Literal ID="lit_retrieveImage" runat="server">Retrieve Image from DB</asp:Literal></b></p><br /> <asp:Image ID="imgFromDB" runat="server" AlternateText="No Image" <br /> GenerateEmptyAlternateText="True" Height="80px" Width="80px" /><br /> <br /><br /> <br /><br /> <asp:Button ID="btn_retrieveImageFromDB" runat="server" <br /> onclick="btn_retrieveImageFromDB_Click" Text="Retrieve Image from DB" /><br /> </div><br /> </form><br /></blockquote><br /><br /><strong>Source Code</strong><br /><br />To store the image to the database, we would need to first convert the .jpeg image to a byte array and then store the record to the database using parameters in the insert statement. If you try to execute a direct insert statement, the .net throws an error as it does not recognizes the byte[] format in the insert statement. Try it!<br /><br />Below is the source code to first get the image path from the FileUpload control that the user selects, and then read the input stream of the image to a byte[] array. Then store the byte[] into the column of type Image.<br /><br />Please include the required error handling in the code below.<br /><br /><strong>Source code to store/save image to the Database</strong><br /><br /><blockquote><br /> private void StoreImageinDB(FileUpload flUpload)<br /> {<br /> SqlConnection _sqlConnection = new SqlConnection();<br /> SqlCommand _sqlCommand = new SqlCommand();<br /> <br /> _sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["StoreImgConnString"].ConnectionString;<br /><br /> _sqlConnection.Open();<br /><br /> _sqlCommand.Connection = _sqlConnection;<br /><br /> string SQLString = "Insert into ImageStore (imgDescription, type, image) values (@imgDescription, @type, @Image)";<br /> _sqlCommand.CommandText = SQLString;<br /><br /> _sqlCommand.Parameters.AddWithValue("@imgDescription", "Humpback Whale");<br /> _sqlCommand.Parameters.AddWithValue("@type", "jpeg");<br /><br /> //create byte[] of length equal to the inputstream of the selected image.<br /> byte[] imageByte = new byte[flUpload.PostedFile.InputStream.Length + 1];<br /> flUpload.PostedFile.InputStream.Read(imageByte, 0, imageByte.Length);<br /> _sqlCommand.Parameters.AddWithValue("Image", imageByte);<br /><br /> _sqlCommand.ExecuteNonQuery();<br /><br /> _sqlConnection.Close();<br /> }<br /><br /> protected void btn_storeImageInDB_Click(object sender, EventArgs e)<br /> {<br /> FileUpload _fileUpload = (FileUpload)this.FindControl("FileUpload_images");<br /> if (_fileUpload.HasFile)<br /> {<br /> StoreImageinDB(_fileUpload);<br /> }<br /> else<br /> {<br /> Response.Write("Please select an image file");<br /> }<br /> }<br /><br /></blockquote><br /><br />As in the code above, the PostedFile.Inputsteam represents the stream of the image selected. And using the Read method, the image stream is read into the byte[].<br /><br /><strong>Source to retrieve image from the Database</strong><br /><br />The below code shows how to retrieve the image from the database. <br /><br /><blockquote><br /> protected void btn_retrieveImageFromDB_Click(object sender, EventArgs e)<br /> {<br /> RetrieveImageFromDB();<br /> }<br /><br /> private void RetrieveImageFromDB()<br /> {<br /> imgFromDB.ImageUrl = "ImageURL.aspx";<br /> }<br /></blockquote><br /><br />From the database, we retrieve the image in the byte[] array format. But the Image Server Control needs the ImageURL. Hence, as seen in the RetrieveImageFromDB() method, you specify a new .aspx page that would contain the logic to get the image from the database.<br /><br />Create a new page in the project named ‘ImageURL.aspx’ which would have the below code on page_load() event.<br /><br /><strong>ImageURL.aspx</strong><br /><br /><blockquote><br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> SqlConnection _sqlConnection = new SqlConnection();<br /> SqlCommand _sqlCommand = new SqlCommand();<br /><br /> _sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["StoreImgConnString"].ConnectionString;<br /> _sqlConnection.Open();<br /> _sqlCommand.Connection = _sqlConnection;<br /><br /> string SQLString = "select top 1 * from ImageStore";<br /> _sqlCommand.CommandText = SQLString;<br /><br /> SqlDataReader _sqlDataReader = _sqlCommand.ExecuteReader();<br /><br /> //we need to typecast to byte[] before feeding it to BinaryWrite method.<br /> if (_sqlDataReader.Read())<br /> {<br /> Response.BinaryWrite((byte[])_sqlDataReader["Image"]);<br /> }<br /><br /> _sqlDataReader.Close();<br /> _sqlConnection.Close();<br /> }<br /></blockquote><br /><br />Here we use Response.BinaryWrite method to write the byte[] array image data to the HTTP output stream. So when this page (ImageURL.aspx) is being referred by the Image control (ImageURL property), the page_load() event fires, and it gets in return the byte[] array image data back to the Image control which displays the image as seen in the page below.<br /><br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiP_savHrgP5TCDKE71gEqijrYjVitgybVDJ72pnQWTPI-uth_U7DP98X6RYz54BB5gSateQsNmMdHuCjYxTiTeFVS3UeoivwbM_2Z5CCORLnLW2o4pErvDJrbn3YE6LiVnBaFN_-7DDdRx/s1600-h/fig2.jpg"><img style="cursor:pointer; cursor:hand;width: 320px; height: 256px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiP_savHrgP5TCDKE71gEqijrYjVitgybVDJ72pnQWTPI-uth_U7DP98X6RYz54BB5gSateQsNmMdHuCjYxTiTeFVS3UeoivwbM_2Z5CCORLnLW2o4pErvDJrbn3YE6LiVnBaFN_-7DDdRx/s320/fig2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5338493543157862354" /></a><br /><br />Enjoy Coding!Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-2826975304604389886.post-32610459880394614142009-05-18T16:49:00.000-07:002009-07-20T15:46:07.304-07:00LINQ to SQL Overview<strong>Introduction</strong><br /><br />Now what is this new thing? As we all know that every day we have something new coming up. It is the new way to access data from the SQL. LINQ to SQL got introduced in VS 2008, .Net Framework 3.5. Hence update your visual studio to this version before you can work on LINQ to SQL.<br /><br />First thing before we start, Please forget everything about ADO.Net concepts so that you don't try to relate any of its concepts with LINQ to SQL internals.<br /><br /><strong>Overview</strong><br /><br />LINQ to SQL uses an Entity-based Framework. It uses a DataContext that contains one or more entity classes. These classes contain public properties that map to each column of the database table that they map to. When we execute LINQ to SQL queries and retrieve data from database, instances of these entity objects get created for each row in that SQL table. You do not have to do all this work, the whole process is internally taken care by the DataContext object.<br /><br />If you are new to LINQ to SQL, you may not understand some of the above mentioned <br />terminologies. In short, DataContext is required which helps retrieve data from the <br />database and also submits our changes back to the data to the database. <br /><br />Lets see a step-by-step example and relate to what we have read.<br /><br /><strong>Example</strong><br /><br />a. Lets say we have a Countries table in SQL as below. We will use LINQ to SQL query to retrieve the countryName values from Countries table.<br /><br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirzr49AF34UKar-UOpcRNI0BetUPcFi1CQ-szWYnpBcMPUXwcuum6U4pUPv0YCA1FkKG720Pw3SFMl9qigmMo42VLEveYi0-x_DZ71tCzH63sPhYoaSRpXBKeJA5KEyfVHeYbNQTX12rad/s1600-h/fig1.jpg"><img style="cursor:pointer; cursor:hand;width: 200px; height: 160px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirzr49AF34UKar-UOpcRNI0BetUPcFi1CQ-szWYnpBcMPUXwcuum6U4pUPv0YCA1FkKG720Pw3SFMl9qigmMo42VLEveYi0-x_DZ71tCzH63sPhYoaSRpXBKeJA5KEyfVHeYbNQTX12rad/s200/fig1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5337316778107328242" /></a><br /><br />Here we will work on a simple console application mainly to display the data that we retrieve using LINQ to SQL.<br /><br />b. Add new item to the project called 'LINQ to SQL Classes'. This creates a .dbml file. Select the .dbml file to load the Object Relational Designer (ORD). Drag and drop the Countries table from Server Explorer to the ORD.<br /><br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhN5d8rQisP_sHTd1HYFneNrM9L5iSwc-SdN4YDqn0wuRgzqdpQnjQOboGJg9rbq1FmV2jCnrHWZms63cWISMSp8tLTy9Cqwa4z6WRKC0HE5N8WxxS-BShoeJhEPIP5OwhiaDocjj6rtqRN/s1600-h/fig2.jpg"><img style="cursor:pointer; cursor:hand;width: 200px; height: 160px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhN5d8rQisP_sHTd1HYFneNrM9L5iSwc-SdN4YDqn0wuRgzqdpQnjQOboGJg9rbq1FmV2jCnrHWZms63cWISMSp8tLTy9Cqwa4z6WRKC0HE5N8WxxS-BShoeJhEPIP5OwhiaDocjj6rtqRN/s200/fig2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5337317061340813842" /></a><br /><br />As we dropped the Countries table, it creates the Countries DataContext underneath (can be viewed in Countries.designer.cs file). Using the instance of this DataContext object we can read and update data to and from the database.<br /><br />As we see above, the Country Entity class gets created and it has public properties that map directly to the columns of Countries table. In our code we would use this entity class that stores the data retrieved from SQL table using the CountriesDataContext.<br /><br />c. Sourcecode:<br /><div class="postCode"><br />using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br /><br />namespace linqtosql<br />{<br /> class Program<br /> {<br /> static void Main(string[] args)<br /> {<br /> GetCountries();<br /> }<br /><br /> Public static void GetCountries()<br /> {<br /> //Create instance of the Countries DataContext class.<br /> CountriesDataContext _countriesDataContext = new CountriesDataContext();<br /><br /> try<br /> {<br /> //Prepare the query to retrieve the data from Countries table<br /> var resCountries = from c in _countriesDataContext.Countries<br /> select c;<br /><br /> //Execute the SQL Query and print the CountryName values<br /><br /> //Also here the CountryDataContext creates<br /> //instances of Country class with data values for each row of data <br /> //in the Countries table.<br /> foreach (var resCountry in resCountries)<br /> {<br /> Console.WriteLine(resCountry.CountryName);<br /> }<br /> Console.Read();<br /> }<br /> catch (Exception ex)<br /> {<br /> Console.Write(ex.Message);<br /> Console.Read();<br /> }<br /> }<br /> }<br />}<br /></div><br /><br /><strong>Optional</strong><br /><br />This is one way of creating DataContext and the Entity Classes. You can also create them on your own, without any tool. Refer <u>http://msdn.microsoft.com/en-us/library/bb386940.aspx</u> for more information about creating manually DataContext & Entity Classes, map them to the database table and query to get the data in the similar way as above.<br /><br />In the <u>next article</u> we will see some of the common SQL-like operations using LINQ to SQL like how to insert, update, delete, and read using filters, sorting, grouping.<br /><br /><strong>References: </strong>http://msdn.microsoft.com/en-us/library/bb386976.aspxUnknownnoreply@blogger.com1tag:blogger.com,1999:blog-2826975304604389886.post-52299596818662767962009-05-16T09:58:00.000-07:002009-07-20T15:46:07.372-07:00Cannot connect to LOCAL/SQLEXPRESS SQL Server on Windows Vista MachineIf you are using Windows Vista OS & SQL Server 2005 on your local system and if you are having a hard time to connect to <Machine-name>/SQLEXPRESS SQL Server with error message - "Can't connect to SQL Server", then <strong>the culprit is SQL Express 2005 SP1</strong>.<br /><br />Download SQL Express 2005 SP1 from the below site and try reconnecting, you will say c'mon, don't tell me this was the issue :)<br /><br />http://www.microsoft.com/downloads/details.aspx?FamilyId=11350B1F-8F44-4DB6-B542-4A4B869C2FF1&displaylang=enUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-65673480311769270332009-05-14T00:19:00.000-07:002009-07-20T15:46:07.382-07:00Update IIS Settings using Script<strong>Introduction</strong><br />Internet Information Services (IIS) is a widely used Internet Services Platform for Microsoft Web Applications. The Web Applications are hosted on IIS by creating websites/virtual directories and/or application pools. Various settings need to be configured before and after the application is deployed on IIS. Some of the important settings are TCP Port, SSL Port, Connection Timeout, IIS log files properties, application pool settings and others.<br /><br />Most of us configure these settings by going to the IIS Manager (start->Run->inetmgr) which everyone would be already aware of. But there is another approach to update the IIS Settings and that is using an IIS Admin script. The server administrators would know about its usage but for those who are not aware of this approache, you will believe that its quite easy to use it as well.<br /><br />Lets see the script & related files locations and its usage. In this article, we would see how to read the existing websites, virtual directories (VDs) and app pools (APs) on IIS. Then we will see how to read the values of some their common configuration settings followed by updating the settings. We won't create or delete any websites, VD or APs.<br /><br /><strong>Files and locations</strong><br />The important files here are:<br />a. <strong>adsutil.vbs</strong>: This is THE script to GET or SET configuration settings in IIS.<br /> Located at: C:\Inetpub\AdminScripts\<br /><br />b. <strong>MetaBase.xml</strong>: This file stores the current IIS Settings in the XML Format.<br /> Located at C:\%SystemRoot%\System32\Inetsrv\<br /><br />c. <strong>MBSchema.xml</strong>: This file contains all the properties with their InternalName and datatypes. The internal names correspond to the property name that you would use to update the value using adsutil.vbs script.<br /> Located at C:\%SystemRoot%\System32\Inetsrv\<br /><br />These files should be secured and accessible only to administrators because of wrongly updated may break your web applications. But you need not exactly be worried because the backups of both of these XML Files are being maintained for us to rollback any changes which are located at C:\%SystemRoot%\System32\Inetsrv\History.<br /><br />You can have a quick look at the Metabase files to get familiarized with the common property names and their datatypes that you require to update in IIS.<br /><br />Let us now look at the usage of adsutil.vbs script and GET/SET some of the common properties.<br /><br /><strong>Using the script</strong><br /><u>Commands to Analyze Websites, VDs & APs created on your IIS</u><br />a. The first thing is to <u>list the instances of the websites, VDs and APs</u> created on your iis. Using the instance name, you can target the settings that you need to read or update.<br /><br />The below command enumerates the paths (instances) of all the websites, VDs, APs on your webserver. Using these paths, you can target the settings for the ones that you need to update.<br /><br />c:\Inetpub\Adminscripts>adsutil.vbs enum /P /w3svc<br /><br />The result will be something like this:<br /><br />[/w3svc/1]<br />[/w3svc/1025764322]<br />[/w3svc/2]<br />[/w3svc/3]<br />[/w3svc/AppPools]<br /><br />where [/w3svc/1], [/w3svc/2], [/w3svc/3] correspond to websites and results like [/w3svc/1025764322] are for VDs. <br /><br />b. <u>Get the details of a particular website</u>.<br /><br />c:\Inetpub\Adminscripts>adsutil.vbs enum /w3svc/1<br /><br />Note: Do not include the /P (path) switch.<br /><br />In the result, you will see the values of various configuration settings as in your IIS Manager for a website. The website name is determined by the 'ServerComment' property.<br /><br />c. <u>Get the details of a particular virtual directory</u>.<br /><br />c:\Inetpub\Adminscripts>adsutil.vbs enum /w3svc/1025764322<br /><br />d. <u>Read or update the details of specific property values</u>.<br /><br />Use GET to read and SET to update:<br /><br />1. <u>Get the ServerComment property value</u>. This corresponds to your website name under Default Website.<br />c:\Inetpub\Adminscripts>adsutil.vbs GET /w3svc/1/ServerComment<br /><br />2. <u>Get the ServerBindings property value</u>. This is corresponding to the TCP Port value in the website tab of your website.<br />c:\Inetpub\Adminscripts>adsutil.vbs GET /w3svc/1/ServerBindings<br /><br />3. <u>Get the SecureBindings property value</u>. This is corresponding to the SSL Port value in the website tab of your website.<br />c:\Inetpub\Adminscripts>adsutil.vbs GET /w3svc/1/SecureBindings<br /><br />4. <u>Disable the Basic Authentication</u>.<br />c:\Inetpub\Adminscripts>adsutil.vbs SET /w3svc/1/AuthBasic "False"<br /><br />5. <u>Set the ConnectionTimeout value to 120 seconds</u>.<br />c:\Inetpub\Adminscripts>adsutil.vbs SET /w3svc/1/ConnectionTimeout 120<br /><br />e. <u>Get the list of App Pools</u>.<br /><br />c:\Inetpub\Adminscripts>adsutil.vbs enum /P /w3svc/AppPools<br /><br />The above command gets the existing App Pools. To read or update the property value of an app pool, use GET or SET commands as shown in section d.<br /><br />c:\Inetpub\Adminscripts>adsutil.vbs GET /w3svc/AppPools/<AppPoolName>/<InternalName><br /><br />The commands are easy to use and also you can get hold of the website, VDs or APs whose settings you need to update using the /P (path) in the command. <br /><br />The only thing you need to know is the exact InternalName (PropertyName), that you can use in your commands. You can either refer to your Metabase xml file or for a quick check you can also use the below command and search through the appropriate name. Its result will have most of the common property names and their datatypes listed for you.<br /><br />c:\Inetpub\Adminscripts>adsutil.vbs enum /w3svc<br /><br />Isn't it easy and straightforward? Hope this makes your life easy and makes you happy too. Have fun!<br /><br /><strong>References</strong><br />http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d3df4bc9-0954-459a-b5e6-7a8bc462960c.mspx?mfr=trueUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-2826975304604389886.post-23614580694554953902009-04-23T23:12:00.000-07:002009-07-20T15:46:07.392-07:00Add/Remove nodes or elements to an XML DocumentIn the article, <a href="http://techiecocktail.blogspot.com/2009/04/update-nodes-and-attributes-in-xml.html">Update nodes and attributes in Xml document</a>, we saw how to update an element or an attribute value in an Xml Document. It requires you to have a pointer to the node or attribute to update before you can update its value.<br /><br />Lets say you want to add a new node section to an existing Xml document. For example lets take the same Xml file as used in the earlier article. It contains list of books, each having its name, author and price values. Say you want to add a new book & its details to the existing list of books.<br /><br /><strong>Xml File</strong>: books.xml<br /><?xml version="1.0"?><br /><books><br /> <book name="asp.net"><br /> <author>John</author><br /> <price>35</price><br /> </book><br /></books><br /><br />To add a new node, you don't require to have any pointer using XPath. XMLDocument, XMLElement and its properties and method does it all. We will first see how to add a new book section. After that we will remove the first one using C#.<br /><br /><strong>Add a new node</strong><br /><blockquote><br />static void Main(string[] args)<br />{<br /> string fileName = @"d:\books.xml";<br /><br /> XmlTextReader _xmlTextReader = new XmlTextReader(fileName);<br /> XmlDocument _xmlDocument = new XmlDocument();<br /> _xmlDocument.Load(_xmlTextReader);<br /> <br /> //Note: Close the reader object to release the xml file. Else while saving you will get an error that it is <br /> //being used by another process.<br /> _xmlTextReader.Close();<br /><br /> addNode(fileName, _xmlDocument);<br />}<br /><br />static void addNode(string fileName, XmlDocument xmlDoc)<br />{<br /> XmlElement bookElement = xmlDoc.CreateElement("book");<br /> bookElement.SetAttribute("name", "DotNet Made Easy");<br /><br /> XmlElement authorElement = xmlDoc.CreateElement("author");<br /> authorElement.InnerText = "microsoft";<br /> bookElement.AppendChild(authorElement);<br /><br /> XmlElement priceElement = xmlDoc.CreateElement("price");<br /> priceElement.InnerText = "50";<br /> bookElement.AppendChild(priceElement);<br /><br /> xmlDoc.DocumentElement.AppendChild(bookElement);<br /> xmlDoc.Save(fileName);<br />}<br /></blockquote><br />Your Xml file should have new book added and should look like below.<br /><br /><strong>Xml File</strong>: books.xml<br /><?xml version="1.0"?><br /><books><br /> <book name="asp.net"><br /> <author>John</author><br /> <price>35</price><br /> </book><br /> <book name="DotNet Made Easy"><br /> <author>microsoft</author><br /> <price>50</price><br /> </book><br /></books><br /><br /><strong>Remove a node</strong><br />Now lets remove the book - 'asp.net' from the list. The deleteNode() method below will remove the book node whose name="asp.net". Using XPath query we create a pointer to the node that needs to be removed. As book is the child node of the books (root element), RemoveChild() helps to remove the book (child node) from the books (root element).<br /><blockquote><br />static void deleteNode(string fileName, XmlDocument xmlDoc)<br />{<br /> XmlElement _xmlElement = xmlDoc.DocumentElement;<br /><br /> XmlNode _xmlNode = _xmlElement.SelectSingleNode("book[@name='asp']");<br /> _xmlElement.RemoveChild(_xmlNode);<br /> xmlDoc.Save(fileName);<br />}<br /></blockquote><br /><br />As seen from these examples it has become easy to perform almost every Xml task with the use of XML classes in .Net. Happy Coding!Unknownnoreply@blogger.com4tag:blogger.com,1999:blog-2826975304604389886.post-37483509037748425452009-04-22T23:09:00.000-07:002009-07-20T15:46:07.403-07:00Update nodes and attributes in a Xml document<strong>Introduction</strong><br />Xml is widely used in application systems to store and receive data, feeds or for some configuration details. There may be times when you need to update some node or element value or update an attribute value. In this article how you can update node or attributes values in an Xml document.<br /><br /><strong>Approach</strong><br />To update the value of a node or an attribute, you need to first create a pointer or a reference to that node containing the element or attribute that requires an update using XPath query. And once you get the pointer to that node, you can access the node or the attribute and set its value to the new value.<br /><br /><strong>Example</strong><br />Lets take a sample Xml file and try to update one of the elements and attributes value using C#.<br /><br /><strong>Xml file</strong>: books.xml<br /><?xml version="1.0"?><br /><books><br /> <book name="asp.net"><br /> <author>John</author><br /> <price>40</price><br /> </book><br /></books><br /><br />Lets see how to update an element and an attribute value as in the below sections. In C# the XML Classes can be found in System.Xml namespace.<br /><br /><strong>Updating an element's value</strong><br />Lets say you need to update the price of the book named asp.net, as in the above Xml document, to a promotional rate from 40 to 35. The below example shows it.<br /><blockquote><br />static void Main(string[] args)<br />{<br /> string fileName = @"d:\books.xml";<br /><br /> //read the Xml file<br /> XmlTextReader _xmlTextReader = new XmlTextReader(fileName);<br /><br /> //load the Xml file into the XmlDocument object<br /> XmlDocument _xmlDocument = new XmlDocument();<br /> _xmlDocument.Load(_xmlTextReader);<br /> <br /> //Note: Close the reader object to release the xml file. Else while saving you will get an error that it is <br /> //being used by another process.<br /> _xmlTextReader.Close();<br /><br /> //update the element (price of the book - asp.net)<br /> updateElement(fileName, _xmlDocument);<br />}<br /><br />static void updateElement(string fileName, XmlDocument xmlDoc)<br />{<br /> //get the root element of the document<br /> XmlElement rootElement = xmlDoc.DocumentElement;<br /><br /> //create a pointer/reference to the price node for the book named 'asp.net'<br /> XmlNode priceNode = rootElement.SelectSingleNode("/books/book[@name='asp.net']/price");<br /> priceNode.InnerText = "35";<br /><br /> //save the Xml<br /> xmlDoc.Save(fileName);<br />}<br /></blockquote><br />In the above example, as in the UpdateElement() method, first the pointer is created to the price node of the book named 'asp.net'. Using that pointer its value is updated by accessing its InnerText (get/set) property.<br /><br /><strong>Updating an attribute's value</strong><br />Lets say the book name has been changed from 'asp.net' to 'Asp.Net Made Easy'. Lets see how to update the name attribute to the new name in the above Xml.<br /><blockquote><br />static void Main(string[] args)<br />{<br /> string fileName = @"d:\books.xml";<br /><br /> //read the Xml file<br /> XmlTextReader _xmlTextReader = new XmlTextReader(fileName);<br /><br /> //load the Xml file into the XmlDocument object<br /> XmlDocument _xmlDocument = new XmlDocument();<br /> _xmlDocument.Load(_xmlTextReader);<br /> <br /> //Note: Close the reader object to release the xml file. Else while saving you will get an error that it is <br /> //being used by another process.<br /> _xmlTextReader.Close();<br /><br /> //update the element (book name)<br /> updateAttribute(fileName, _xmlDocument);<br />}<br /><br />static void updateAttribute(string fileName, XmlDocument xmlDoc)<br />{<br /> //get the root element of the document<br /> XmlElement rootElement = xmlDoc.DocumentElement;<br /><br /> //Update the name attribute's value<br /> XmlNode bookNode = rootElement.SelectSingleNode("/books/book[@name='asp.net']");<br /> if (bookNode.Attributes["name"].Value.Equals("asp.net"))<br /> {<br /> bookNode.Attributes["name"].Value = "Asp.Net Made Easy";<br /> }<br /><br /> //save the Xml<br /> xmlDoc.Save(fileName);<br />}<br /></blockquote>Unknownnoreply@blogger.com5