Posts

Showing posts from 2011

Donate

Using Microsoft.VisualBasic DateDiff() Function In Your C# Program

Below is a snippet on how to use the Microsoft.VisualBasic DateDiff() Function in your C# program. Add the Microsoft.VisualBasic reference to your project so that you can access it's underlying classes and methods. long age = Microsoft.VisualBasic.DateAndTime.DateDiff( "yyyy" ,Convert.ToDateTime( "1985-04-04" ),DateTime.Now);

How To Decode An Encoded URL In C#.NET

The code below illustrates how to decode an encoded url using HttpUtility.UrlDecode(string url) using System.Web; //make sure to add reference to System.Web string temp_url = "http%3a%2f%2fplacement.emploiquebec.net%2f" + "mbe%2fut%2fsuivroffrs%2fapercoffr.asp" + "%3fnooffr%3d3053675%26page%3drech%26prov% 3derechroffr%252Easp%26CL%3denglish "; string url = HttpUtility.UrlDecode(temp_url);

Read Or Parse XML Using XmlElement Class, XPath And XmlNodelist In C#

Sample xml file: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?xml version="1.0" encoding="UTF-8"?> <jobs> <job> <title> Payroll Analyst </title> <description> <summary> Seeking Payroll Analyst specialists. Great benefits and competitive salary. Must meet all requirements to be considered for assignment. </summary> </description> <location> <state> Pennsylvenia </state> </location> </job> <job /> </jobs> Code: 1 2 3 4 5 6 7 8 9 10 11 ListingSource = webclient.DownloadString( "your_xmlurl" ); StringReader readString = new System.IOStringReader(ListingSource); XmlDocument awesome = new XmlDocument(); awesome.Load(readString); XmlNodeList nodeList = awesome.SelectNodes( "//jobs/job" ); foreach (XmlElement element in nodeList) { title = elem

(502)Bad Gateway Returned From HttpWebRequest In C#

The solutions is to set the default proxy for the web request and assign user agent to it as shown below: ListURL = String.Format( "your_xml_feed_or_API_url_sample" ); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ListURL); request.Timeout = 900000000; request.Proxy = HttpWebRequest.DefaultWebProxy; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)" ; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); ListingSource = reader.ReadToEnd(); ListingSource = System.Web.HttpUtility.HtmlDecode(ListingSource); Cheers!

Invalid Expanded Name In LINQ to XML

Assuming I am reading this xml file using XLINQ. I encountered an error that says invalid expanded name. As i go through this xml file, i found a node images that contains element tags. The parent node is also an element tag. Since i don't use the images tag, I simply remove it using string manipulations. Below is the xml file and the solution: <element> <id> 2768687195 </id> <title> Customer Service Representative </title> <body> Do you dream of being your own boss and choosing the work you do, when you work and who you work for? </body> <url> http://jobs.myjob.careercenter-servicecrew.html </url> <category> <id> job/customer_service </id> <name> Customer Service &amp; Call Center Jobs </name> </category> <source> <id> www </id>

How To Read Or Parse XML Using LINQ And XLinq In C#

Hello, Here's an example on how to read or parse XML file using LINQ and XLINQ in C#. XML Content: <item> <title> Labor Warehouse Associates - Boston, Massachusetts </title> <link> http//www.BostonRecruiter.com/job_display.php?alpha=17343491 </link> <description> Hudson Group is the #1 airport retailer operating in over 400 retail locations in most major airports, throughout the US and Canada. While we are comprised of many </description> <guid> http//www.BostonRecruiter.com/job_display.php?alpha=17343491 </guid> <joblocation> <jobcity> Boston </jobcity> <jobstate> Massachusetts </jobstate> <jobcountry> United States </jobcountry> </joblocation> </item> C# Code: string url = "your xml or rss link" ; string xmlsource = client.DownloadString(url);

Manipulate Object Property Using Lambda Expression In LINQ

Here's how to manipulate or update an object property using Lambda format in LINQ. In this example, I assigned a value to the textbox control's Text property using a delegate that applies the concept of Lambda expressions in LINQ. ShowEmployeeDelegate d = () => { tMessage.Text = "Nelson" ; }; d.Invoke();

Remove Open And Close Square Brackets In A Sentence Using Regular Expression In C#

Given the sample string data [Posted Friday September 23 2011] and you need format the sentence like this Posted Friday September 23 2011 without the square brackets, a solution would be to use Regex. string date = Regex.Replace(date, "[\\[\\]]" , string .Empty); date = Regex.Replace(date, @"[\[\]]" , string .Empty);

Replace Character In A String Based On Specific Index In C#

Here's an example snippet that will replace a character based from a specific index. Source: DreamInCode To use it in your program do it like this: // Replaces a character in a string with the character specified. void replaceCharWithChar( ref string text, int index, char charToUse) { char [] tmpBuffer = text.ToCharArray(); buffer[index] = charToUse; text = new string (tmpBuffer); } //IN YOUR MAIN MODULE/FUNCTION. //money has comma, example: $2,000, 4 BR, 180 m² //LandPriceBedroom = "$120, 2 BR, 90 m²"; //IF COMMA OCCURS MORE THAN TWO, REPLACE THE FIRST //COMMA WITH SPACE. SINCE IT COULD BE A MONEY W/ //THOUSANDS SEPARATOR if (LandPriceBedroom.Split( ',' ).Length > 3) { int firstIndexComma = LandPriceBedroom.IndexOf( "," ); replaceCharWithChar( ref LandPriceBedroom, firstIndexComma, ' ' ); }

Regular Expression Remove String With A Punctuation Beside It In A Sentence In C#

Assuming in a sentence, you want to remove the word apply now in any case. This word has a punctuation beside it. Example: Apply now! Apply now. APPLY NOW! APPLY NOW. apply Now! apply Now. In a sentence: We are in need of VB.NET Developers. Apply Now! We are in need of VB.NET Developers. Apply now! We are in need of VB.NET Developers. APPLY NOW! We are in need of VB.NET Developers. apply now! To remove, just use the code below: description = Regex.Replace(description, "apply now[!.]" , string .Empty,RegexOptions.IgnoreCase).Trim(); Note: I'm not a Regex expert.

Remove Dotted Lines Or Whitespaces In Visual Studio 2010

Good evening gents! Use the shortcut keys below to remove the dotted lines or white spaces in your Visual Studio 2010 IDE: 1. ctrl r+w or 2. ctrl e+s Cheers!

Uncompress GZip Response Using WebClient In C#

In a scenario where you want to download xml data using webclient, the response from firefox or any browser will display the xml file correctly. However, using a web request/webclient.downloadstring to download the xml file, the response is somewhat corrupted or in hashed form. The response headers are the following: 1. Content-Type - application/xml 2. Content-Encoding - gzip As you can see, the content encoding is of type gzip . The solution is to override the web request method to something like this: class DecompressGzipResponse : WebClient { protected override WebRequest GetWebRequest (Uri address) { HttpWebRequest request = (HttpWebRequest) base .GetWebRequest(address); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; return request; } } //to use this in the program (main function) DecompressGzipResponse client = new DecompressGzipResponse (); Listi

How To Convert Exponent to Decimal Notation In C#

Good morning, Here's how you convert exponent value to C# using decimal.parse() function. Make sure to pass NumberStyles.Float from System.Globalization namesapce in the second parameter of the function. string land_area = "1.21445e-007" .ToUpper(); decimal dec = decimal .Parse(land_area, System.Globalization.NumberStyles.Float);

How To Count Number Of Character Or ElementOccurrences In A String Using C#

Hello All, In order to count the occurences of a certain element or character in a string, you need to perform the split() function and subtract the length with one to get the actual count. int count_li = tempListSource.Split( new string []{ "<li>" }, StringSplitOptions.RemoveEmptyEntries).Length - 1;

Reset Seed In MySQL Table

To reset the seed of a MySQL table, perform alter table statement and set the AUTO_INCREMENT value to 1. ALTER TABLE tblProduct AUTO_INCREMENT = 1; Cheers!

.NET Framework Version Checker in your PC Using C#

Here's a repost of a .NET Version Checker I found in the internet. const string regLocation = "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP" ; static void Main( string [] args){ Console.WriteLine( ".NET Framework versions installed" ); Console.WriteLine( "---------------------------------" ); Console.WriteLine(); RegistryKey masterKey = Registry.LocalMachine.OpenSubKey(regLocation); RegistryKey tempKey; if (masterKey == null ) { Console.WriteLine( "Null Key!" ); } else { string [] SubKeyNames = masterKey.GetSubKeyNames(); for ( int i = 0; i < SubKeyNames.Length; i++) { tempKey = Registry.LocalMachine.OpenSubKey (regLocation + "\\" + SubKeyNames[i]); Console.Write(SubKeyNames[i]); Console.WriteLine( "\t

The Error: 417 "Expectation Failed." During Webrequest In C#

Here's a solution on how to fix the 417 expectation failed error during WebRequest In C#. System.Net.ServicePointManager.Expect100Continue = false ;

How To Insert Date Object In MySQL Using C#.NET

Hello, To insert date object using C#.net in MySQL db,use the code below: string query = String.Format( "Insert into tbllistings(DateRegistered)" + "values(DATE_FORMAT({0}, '%Y-%m-%d %h:%m:%s'))" ,objJobs.DateRegistered); The key to the solution is using the MySQL Date format function.

Disable WindowsForms Form From Being Resized At Design Time In C#

Here's a snippet on how to prevent or disable winforms form object from being resized at design time. this .MaximumSize = new System.DrawingSize(500, 400); this .MinimumSize = new System.DrawingSize(500, 400);

MySQL Date Range Query (Using Logical Operators)

Here's another version using logical operators in MySQL. 1: select date_format(date_purchased, '%m/%d/%Y' ) as dates, 2: url from dbcommerce.tblproducts 3: where date_format(date_purchased, '%m/%d/%Y' ) >= '04/30/2011' 4: and date_format(date_purchased, '%m/%d/%Y' ) <= '05/30/2011' 5: order by date_purchased asc ;

MySQL Date Range Query Example

Here is an example to query MySQL Date Range given the date field is of type TimeStamp. The date_format() will remove the time part in comparing. select date_format(date_purchased, '%m/%d/%Y' ) as dates, url from dbCommerce.tblproducts where date_format(date_purchased, '%m/%d/%Y' ) between '04/30/2011' and '05/30/2011' order by date_purchased asc ;

Unable To Convert MySQL DateTime Value To System.DateTime In C# Or ASP.NET

Solution: Add Allow Zero to your Web.Config or App.Config <add key= "connectionString" value= "Database=your_db ;Data Source=localhost;User Id=root; Password=password;Allow Zero Datetime=True;" /> Cheers!

Newline For C# Equivalent With Environment.Newline

txtOutput.Text = "Select All Nodes" + "\r\n" ; //or txtOutput.Text = "Select All Nodes" + Environment.Newline;

Setup SQL Developer To Connect To A MySQL Database

1. Download sql developer from oracle site 2. Copy sql developer to drive C:\ 3. Copy msvcr71.dll to %WinDir%\System32 [reference: http://gisbiz.com/2011/05/fixing-the-sql-developer-msvcr71-dll-error/] msvcr71.dll is located in: [sqldeveloper\jdk\jre\bin\msvcr71.dll] 4. Download mysql-connector-java-5.0.8-bin.jar zip file from this site: Download MySQL connector Java 5. Extract mysql-connector-java-5.0.8-bin.jar in sql developer lib folder: C:\Users\gnesguerra\Downloads\sqldeveloper-3.0.04.34\sqldeveloper\lib 6. Setup sql developer to connect to mysql database using the tutorial from this site: Starting from Setting it Up Paragraph: Configuring SQL Developer for MySQL    6.1 Click Choose Database button below Port label.    6.2 Beside the Choose Database button, select the database you want to connect to from the dropdown control.    6.3 Zero Date Handling should be set to null    6.4 Click Connect 7. (Increase Operation Timeout)    7

Retrieve Record Counts For All Tables In MySQL DB

Reference: Get Record Counts for All Tables in MySQL

Using Proxy With WebClient In VB.NET

Here is a snippet to use WebProxy. This is useful for scraping or other webrequest activities. Dim webclient As New System.Net.WebClient Try 'true for bypassOnLocal webclient .Proxy = New System.Net.WebProxy( "180.95.129.232:80" , true ) wc.OpenRead( "http://yoursite.com" ) lblStatus.Text = "ok" Catch lblStatus.Text = "error proxy" End Try

Format Query Result By Count() With Comma Using Format() In MySQL Database

I played around with MySQL count() statement. I found it annoying that the count() will simply return whole numbers. Example: the total record of a table is 32,272. In MySQL SQL, this will simply return 32272. Below are two sql scripts. The first one returns whole number,while the second query returns comma separated number. ENJOY!!!! select count (*) as num_records_notformatted from mytable where name like '%j%' ; Solution: select format( count (id),0) as num_records_formatted from mytable where name like '%j%' ;

How To Set The Scrollbars In WPF Textbox

You can set the scrollbars in a WPF TextBox control using it's properties: HorizontalScrollBarVisibility= "Visible" VerticalScrollBarVisibility= "Auto" or using the ScrollView class: ScrollViewer.HorizontalScrollBarVisibility= "Auto" ScrollViewer.VerticalScrollBarVisibility= "Auto"

Control.InvokeRequired Not Found Or Missing In WPF

Hello, I was doing a little WPF threading recently which involved changing my codes from Winforms to WPF. Surprisingly, I was not able to find the code below in the intellisense: Control.Dispatcher.CheckAccess() After googling, I found this link: Why is Dispatcher.CheckAccess() hidden from intellisense? I wonder why Microsoft hid some features on intellisense. Or it could be a bug. Regards!!!

Webclient - The remote server returned an error: (403) Forbidden

Using downloadstring of webclient returns an error as stated by the post title. The solution was to add user agent header to the webclient headers. The value of user agent can be found in the mozilla firebug. Solution: string URL = string .Format(your_url); newWebClient.Headers.Add( "user-agent" , "Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0 "); string pageSource = newWebClient.DownloadString(URL); pageSource = System.Web.HttpUtility.HtmlDecode(pageSource);

How To Show External IP Address Using C# And WebClient

I experimented a snippet to get my ISP provided IP address using whatismyip. Using tutorials or code snippets from links, the web request just returned a 404 error. After reading the whatismyip API again,they have changed their automation URL. Below is the code snippet. //previous URL present on most tutorials which is not working //string whatIsMyIp = "http://www.whatismyip.com/automation/n09230945.asp"; //updated URL from whatismyip API string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp" ; WebClient wc = new WebClient(); UTF8Encoding utf8 = new UTF8Encoding(); string requestHtml = "" ; requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));

How To Convert Epoch Time To DateTime In C#

Good morning awesome programmers, Me and my fellow teammate encountered a scenario to convert epoch time to datetime. The solution can be found in stack overflow. private void Form1_Load( object sender, EventArgs e) { //long tms = 1308139229; long tms = 1308143650; DateTime dt = FromUnixTime(tms); MessageBox.Show(dt.ToShortDateString()); } public DateTime FromUnixTime( long unixTime) { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return epoch.AddSeconds(unixTime); }

Sorting List<T> Generic Collection String In C#

This example uses List generic collection and will sort names in descending order. Names with New will be displayed on top of the list. This is applicable if you will be displaying products names with NEW in it's product name as recently displayed. List< string > Names = new List< string >(); private void FListSort_Load( object sender, EventArgs e) { Names.Add( "Mike" ); Names.Add( "John" ); Names.Add( "Titch" ); Names.Add( "Harold" ); Names.Add( "Klent" ); Names.Add( "Thomas New" ); Names.Add( "Mary" ); Names.Add( "Fultron New" ); Names.Add( "Khayce" ); Names.Add( "Tim" ); Names.Add( "Joker New" ); Names.Add( "Linda" ); Names.Add( "Arthur New" ); Names.Add( "Baby Lee Jones"

Posting Data To WebBrowser Control In C#

Good day! Basically, it is possible to post data to web browser control using C#. The code below, was referenced from MSDN, but i slightly modified some of it's functionalities. string url = "http://example.com" ; string postData = String.Format( "city=DC&Page={0:00}" ,pageNum); byte [] Post = Encoding.UTF8.GetBytes(postData ); string AdditionalHeaders = "Content-Type: application/x-www-form-urlencoded" ; //wbSample is the web browser control //the WebNavigate method is just a simple method i created //which simply assigns url to the browser, the post data and additional headers WebNavigate(wbSample , ListURL, "" , Post, AdditionalHeaders);

JQuery Calculator Example In ASP.NET Web Forms

Image
The image above is a jquery/javascript calculator developed in ASP.NET 4.0 web template. Here's the functions. I'wont be posting all codes since it will took up space in my post. I'll just post the sqrt() and a number scripts. The ASPX markup uses plain css for centering and aligning the buttons and html controls. No asp.net server controls are involved. For the jquery processing, im using the id selector. /* show zero to textbox on page load */ $( "#txtCalc" ).ready( function () { $( "#txtCalc" ).val( "0" ); }); //square root $( "#btnSqrt" ).click( function () { var text = $( "#txtCalc" ).val(); //if invalid input,do not execute codes below if (text.search( "Invalid" ) != -1) { return ; } if (text.length == 1) { if (text == "0" ) { return ; }

Random Class In C#.NET Not Generating Proper X And Y Coordinates

I am creating a snippet to change x and y coordinates upon runtime. However,not as i expected,the generated random numbers does not meet my requirements. Here is the C# snippet: switch (odd_eve) { case 0: Random rand = new Random(); count = rand.Next(0, 300); break ; case 1: Random rand1 = new Random(); count = rand1.Next(310, 600); break ; default : } Based from the code above,the random generates a slanting x and y coordinates. The solution i come up came from the idea of a fellow developer to declare one Random object in one class. Random rand = new Random(); //declared as global variable //function snippet switch (odd_eve) { case 0: count = rand.Next(0, 300); break ; case 1: count = rand.Next(310, 600); break ; default : } Works like a charm!!!

How To Debug JavaScript Code In Visual Studio 2008 Or Visual Studio 2010

Here are the simple steps to debug js code in your aspx markup. 1. Open Visual Studio 2008/2010 2. Click Tools then options 3. Expand debugging node then click checkboxes Manages,Native,Script. 4. In your web.config file,make sure to set compilation debug to true. <compilation debug= "true" > <assemblies> <add assembly= "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> <add assembly= "System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly= "System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> <add assembly= "System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> </assemblies> </compilation> 5. Choo

Microsoft SQL Server, Error 14234

Lately, I installed an SQL Server 2005 database on my clients server machine,and when i created a database maintenance plan,i got the error as stated: The specified '@subsystem' is invalid (valid values are returned by sp_enum_sqlagent_subsystems). (Microsoft SQL Server, Error 14234) The solution is to install SQL Server 2005 Integration Services.

"Installation Incomplete - The installer was interrupted before could be installed. (Visual Studio Web Setup Project)

Hello! Recently, the ASP.NET Web Forms software i maintained crashed down and can't be opened by the browsers (IE,Firefox and chrome). I tried different kinds of solutions but they don't work. So,i tried the steps below to re-install the web setup package with the error provided as the title of the post. Culprit: virus attack[dangerous or high risk worm/trojan] Solution: 1. Repair windows xp sp2 (using installer cd) XP Repair Install Note: I performed only steps 1-6 2. After repairing, I uninstalled the IIS 3. Delete the current Inetpub folder in Drive C:\ [make sure to backup any files in the Inetpub folder] 4. Then restart PC after performing steps 2-3 5. Re-install IIS using windows xp sp2 cd 6. Register asp.net 2.0 from command prompt c:\windows\microsoft.net\framework\v2.0.50727>aspnet_regiis -i 7. Restart PC/Server 8. Continue Installing VS Web Setup Project Note: This may also apply to Windows 2003 server or new Windows OS.

StringCollections In C#.NET

After some tiresome work, i decided to visit MSDN. Along the way,i manage to take a grip from System.Collections.Specialized StringCollection class. I was used to List , ArrayList, and etc. After reading MSDN's documentation,I managed to create a simple example. class Program { static void Main( string [] args) { //defined class StringCollections collections = new StringCollections(); //.NET collection class StringCollection netcollection = new StringCollection(); string [] names = new string [5]; //insert five elements for ( int i = 0; i <5; i++) { names[i] = "nelson" + (i+1); } //store to stringcollection object netcollection = collections.Employees(names); //navigate collection class StringEnumerator enumerator = netcollection.GetEnumerator(); while (enumerator.MoveNext()) {

ASP.NET MVC View Model

I recently read an article from Stephen Walther on View Models and gave it a spin. In this example,i created two typed class namely People and address..You may create properties or public fields in there. After that,create a controller with the view model which has List properties. Then in your view,you simply inherit the PersonViewModel. Below is the Person Controller with the PersonViewModel. public class PersonController : Controller { public ActionResult Index() { // Create list of People var people = new List<People>(); people.Add( new People(30, "Nelson G." )); people.Add( new People(28, "James Ingram" )); // Create list of Address var address = new List<Address>(); address.Add( new Address(9000, "Cebu" )); address.Add( new Address(6521, "Baybay" )); // Return view return View( new PersonVi

Accessing HttpUtility Class In C# Winforms

To use or access the HttpUtility class in C# winforms, do the following: 1. Add reference to System.Web dll 2. Use any methods available in HttpUtility class. System.Web.HttpUtility.HtmlDecode(mystring); System.Web.HttpUtility.UrlDecode(mystring); Cheers!

Using Sessions In ASP.NET Web Forms Web Services

Lately, i was confronted with a problem on managing state with web services, after reading a book on XML in .NET 2.0, i found a tip on creating and consuming web services with state capabilities. I followed this link: Using Session State in a Webservice MSDN: Web Service Session This idea, is a life saver to some of my web projects.. :D

Visual C# 2010 Express (System.Web Namespace Not Found)

When you created a winforms project and you would like to use HttpUtilities or other classes found on System.Web, you might notice that when you tried adding reference to System.Web, it is not found on the .NET Tab. By default, the project is targeted on .NET Compact framework 4.0, so just change it to .NET Framework 4.0. By then,you will be able to add the System.Web namespace in your projects. Cheers

Repair A SQL Server 2008 Suspect Database After Upgrading

Lately, I've installed SQL Server 2008 Developer Edition in my pc and migrated all sql server 2005 databases. Upon attaching/restoring all databases, some were marked as suspect. Below is the sql script to repair those databases. EXEC sp_resetstatus 'Test' ; ALTER DATABASE Test SET EMERGENCY DBCC checkdb( 'Test' ) ALTER DATABASE Test SET SINGLE_USER WITH ROLLBACK IMMEDIATE DBCC CheckDB ( 'Test' , REPAIR_ALLOW_DATA_LOSS) ALTER DATABASE Test SET MULTI_USER But as a precautionary measure,I have back-up plans for each database,as to have another copy when things go wrong. Test is the database name. Source: how-to-repair-sql-server-2008-suspect

Deploying ASP.NET Web Forms Websites Using ASP.NET Membership Framework

In my case, i have been experimenting an e-commerce application which uses asp.net membership framework. If I run the website using visual studio 2008, it successfully logs in using the users i have created using the built-in asp.net website administration tool. However, if you deploy this on a production server such as IIS, you cant' log-in. The solution is straightforward in this link: Always set the "applicationName" property when configuring ASP.NET 2.0 Membership and other Providers(Configuring ASP.NET 2.0 Membership)

How To Clear Sessions After Logout Button Is Clicked In ASP.NET Web Forms

Solution I found is on this link: ASP.NET Forum Link

How To Install IIS On Windows 7 Home Premium

Here's the link: Technet Link

Unable To Open EDMX (Entity Framework in Design View) After Closing

Scenario: You may have recently added an entity framework that maps to an sql server table. After that, you suddenly close it. But when you tried to double click the Entity model, it does not open in the design view. Solution: Cannot Open .edmx file in the designer

Insert Parameter Array in .NET (C# Version)

The first version i created was a vb.net version. Here is the C# version: myConn objCon = Program.connectionstring; string str = objCon(); //pass delegate to string SqlConnection connection = new SqlConnection(str); try { List<Patient>patients = new List<Patient>(); for ( int i = 0; i < 5; i++) { Patient patient = new Patient(); patient.name = "greg" + i; patient.code = i*2; patients.Add(patient); } //insert into array connection.Open(); StringBuilder query = new StringBuilder(); SqlCommand cmd = new SqlCommand(); for ( int j = 0; j < patients.Count; j++) { query.Append( string .Format( "Insert into patients (PatientName,PatientSexCode) values (@names{0},@code{1}); ",j,j));

Change Default Browser Of ASP.NET MVC Project

To change a default browser for an asp.net mvc website to render is not straightforward. However, the steps are just easy: 1. Add a webform or a static html to the application, just leave the default name. 2. Right click on the newly added webform. 3. Click Browse With. 4. Choose the browser like Firefox, IE, or Chrome. 5. Mark it as default. Thats it!!!

How To Get ASP.NET Web Forms GridviewRow Selected Index In Row Command Event

In your row command event, add a code like this: int selected_index = Convert.ToInt32(e.CommandArgument);

How To Cast SQL Money Field Type To C# Data Type

Given you have a field called customer_salary which is of type money in sql server, to cast and use it in your c# programs, you cast it to decimal. decimal Price = Convert.ToDecimal(reader.GetValue(1));

Choosing Between ASP.NET MVC And ASP. NET WebForms

I've been playing around asp.net mvc just recently, i was really shocked and somewhat struggling with this new framework since i was used to the traditional N-Tier development with asp.net. As I developed simple examples, asp.net mvc is somewhat similar to n-tier development. As such, each layers have been separated to enable designers and coders to work independently with each layer. I have some books in my arsenal but i haven't read them yet.LOL Basically, I'm still a newbie with this stuff. One tip that i read was choosing between asp.net webforms and asp.net mvc. This will provide insights on other developers as well. Choosing between ASP.NET MVC and ASP.NET Webforms Source: ASP.NET MVC 1.0 Quickly In general, choosing between ASP.NET MVC and ASP.NET can be based on the following five criteria: 1. Are you considering test-driven development (TDD)? TDD enables you to write tests for an application first, after which the application logic is developed. An ASP.NET Webfor

How To Calculate Age In SQL Server T-SQL Using DATEDIFF()

Here is a script to calculate an age of a person using TSQL using Convert(). SELECT FirstName, LastName , CONVERT (Int, DATEDIFF( day , BirthDate, GETDATE())/365.25) As Age FROM EmployeesDTR Source: TSQL Reference

Login Control Never Redirects To Index Or Default Page In ASP.NET Web Forms

Working with login control in asp.net provides convenient way to apply secured user API with less programming. Since login control is part of .net framework,such classes are provided such as membership, forms authentication and etc.. One weird error i encountered is that, it does not redirect to my index page once login has been successful. I implemented my own validation function to check if a user exists in the database. If the method returns true, redirect to index page. See code below. But the fact is, it does not redirect. if (CheckUserInMyDB(Login1.UserName, Login1.Password)) { e.Authenticated = true ; Login1.Visible = false ; Response.Redirect( "Index.aspx" ); } else { e.Authenticated = false ; } So the solution i found in forums.asp.net was to transfer the Response.Redirect to Logged in method of the login control.

Insert Parameter Array In VB.NET

Here's a snippet to insert a parameter array in .NET: ' add a class ex. Patient Public Class Patient Public name As String Public code As Integer End Class ' create a delegate Delegate Function myConn() As String 'function to return connstring Private Function connectionstring() As String Dim conn As String = "your_connection_string here" Return conn End Function '--Main Sub ' execute insert array Dim objCon As myConn objCon = New myConn( AddressOf connectionstring) Dim str As String = objCon.Invoke() Dim connection As New SqlConnection(str) Try Dim patients As New List( Of Patient) For i As Integer = 0 To max_count_variable Dim patient As New Patient()

Bulk Insert Stored Procedure Not Returning 0 Row(s) Affected (Error)

Lately, A while ago, a friend of mine sent me a CSV file whose fields are separated by comma. I followed a link from http://www.sqlteam.com in creating a stored procedure via BULK INSERT. This complex stored procedure inserts rows from a csv file to a database table with a field defined as primary key (identity seed option set). After changing the script from the website and executed the SP below: use clientdb go EXEC Customer_Import 'D:\Csharp progs\Orders\Client.csv' , 2 The message returned in the result pane was: 0 row(s) affected. Wow, how could this happend where in fact, the csv has 50 rows? I've changed other options to the SP but got no luck. The solution i ran into was to re-open the CSV file and save as another file. Ex. (from Client to Client1). So, when i executed the SP above using the other file, it performed perfectly. use clientdb go EXEC Customer_Import 'D:\Csharp progs\Orders\Client1.csv' , 2 So, I guess there mu

Donate