Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts

Sunday, April 28, 2013

Get the Primary key on Insert Using Entity Framework


Hey guys, this is just a quick code example to show how you can get the auto incrementing Primary Key ID when inserting a new row using Entity Framework.


 
All you need to do is insert the record as you normally would, then after you saveChanges() just assign the ID to an integer as seen below.
 int TaskID;  
 using (var context = new AppName.Data.Matters.MatterContext())  
 {  
   AppName.Data.Matters.Task task = new AppName.Data.Matters.Task();  
   task.TaskCategoryID = Int32.Parse(DrpDwnTaskCategory.SelectedValue);  
   task.CreatedByUserID = UserID;  
   task.DateCreated = DateTime.Now;  
   context.Task.Add(task);  
   context.SaveChanges();  
   TaskID = task.TaskID  
 }  

How easy is that!

Wednesday, April 10, 2013

ASP.NET Postback in jQuery UI Modal Dialog


Why is the postback not working?


When you use the jQuery UI Modal Dialog it pulls the referenced Div out of the form to create the Modal Dialog. As a result  ASP.Net elements such as the asp:Button and asp: TextBox will not function as they need to be in the form for your code behind to access them and the postback to work.

How do we fix it?


The easiest fix is to simply add the Div back to the form. In the code sample below, you will see that I have wired a function to the Open event of my ShowPannelInDialog method that appends the Div to the form.

Code:
<script type="text/javascript">
        function ShowPannelInDialog(PannelID, title) {
            $("#" + PannelID).dialog({
                title: title, 
                modal: true,
                open: function(type, data) { $(this).parent().appendTo("form");  },
                close: function (type, data) { ($(this).parent().replaceWith("")); }
        });
            return false;//prevent hyperlink from going to new page
        }
</script>

<div style="display:none" id="PopupBox">
Cost Name : <asp:TextBox ID="TxtDescription" runat="server"></asp:TextBox>
<asp:Button ID="BtnSubmit" runat="server" OnClick="BtnSubmit_Click" Text="Submit" />
</div>
<a onclick="showPannelInDialog('PopupBox','Title goes here');" href="#">Open Popup</a>

I have also wired a function to the Close event that removes the Div from the form. If you don’t do this then opening the Modal Dialog and closing it without submitting will create duplicates of your Div including the ASP.Net elements.


Did this post help you? Please let me know in the comments or use the buttons below to share it with your social network.

Sunday, March 17, 2013

Writing Better C# Code - If Statements

A very important part of being a good programmer is writing concise and clean code. There are many ways that we can eliminate unnecessary code so I will be writing a few articles about how to write better code, but I will start with the humble “If Statement”.

I think a lot of developers zero in on Objects and Classes in C# because it is an Object Orientated development language, and they don’t bother getting to really know the If Statement. This is a real shame as I consider Conditional Logic to be one of the fundamental building blocks of any application.

Setting a Boolean value


Take a look at this code;
 if (WebUtil.isDebug == true)  
 {  
   btnMerge.Visible = true;  
 }  
 else  
 {  
   btnMerge.Visible = false;  
 }  

When setting a Boolean value based on the value of another Boolean, you don’t need to use the full If Statement. You can use the following shorthand to get the same result;
btnMerge.Visible = (WebUtil.isDebug);

Obviously, if the Boolean values are opposite, you can just use the ! operator as follows;
btnMerge.Visible = (!WebUtil.isDebug);

You can set your Boolean in this way with any If Statement because If Statements always resolve to either true or false;
btnMerge.Visible = ((x<=2)||(y>=6));

Nested If Statements


When you write an If Statement inside another If Statement, it’s called a nested If Statement. There are very few instances that this is actually required and it makes your code unnecessarily bloated and hard to read.

If you spend some time learning to use your C# Operators and apply yourself to the logic you will be amazed how much unnecessary code you can eliminate.

Here is an example of unnecessary nested If Statements. In the following chunk of Conditional Logic only employees can login impersonating end users. When somebody logs in, the app will send a notification only if they are not in the new Database and not impersonating another user and the notification has not already been sent;
 if (Employee)  
 {  
   if (AsSelf)//Employee logging in as self  
   {  
     if (!obj.InNewDB())   
     {  
       if (obj.CheckforSendNotify())   
       {  
         NewDBNotify(loginID);  
       }  
     }  
   }  
   else  
   {  
     //Don’t notify because Employee impersonating user  
   }  
 }  
 else // notify because it’s an end user  
 {  
   if (!obj.InNewDB())   
   {  
     if (obj.CheckforSendNotify())   
     {  
       NewDBNotify(loginID);  
     }   
   }   
 }  

When written properly, that chunk of code becomes;
 if ((Employee && AsSelf) || (!Employee))  
 {  
   if ((!obj.InNewDB()) && (obj.CheckforSendNotify()))  
   {  
     NewDBNotify(loginID);  
   }  
 }  

Setting a default for a null-able value


You can use the ?? operator to set a default for a null-able value or reference. Don’t worry if that didn’t make sense, just keep reading and it should become clear to you.

In the code below, btnMerge.Visible will get it’s TRUE or FALSE value from MyObject.Boolfield, but if MyObject.Boolfield is NULL, btnMerge.Visible will default to FALSE;

 btnMerge.Visible = MyObject.Boolfield ?? false;  

If you enjoyed this post, please let me know by leaving a comment. Even if you disagree with anything I have said here, I value your feedback.

Sunday, October 7, 2012

Visual Studio Tips & Tricks to Streamline Development

Here are a few of my favorite Visual Studio tips & tricks that I use to streamline my development;

Record and play temporary macro


Press Ctrl+Shift+R to record a new temporary macro, then press Ctrl+Shift+R to stop recording.
Ctrl+Shift+P will play the recorded macro.

Previous cursor positions


Ctrl+- (i.e. Ctrl and Hyphen)  cycles you through the code positions that you have visited.
Use Ctrl+Shift+- to navigate in the opposite direction.

Matching brace/comment/region/quote


Ctrl+] takes you to the matching brace. It also takes you to the matching comment, region or quote depending on where your cursor is.

Intellisense suggestions


Press Ctrl+Shift+Space to bring up the intellisense suggestions.

Line numbering


To enable/disable Line number go to Tools|Options|Text Editor|All Languages|General|Line numbers.

If you want to set this option for only one language, then choose the appropriate language instead of All Languages.

Code Snippets


There are Code Snippets for most methods that get used often. To try this, type “for”, and then hit you tab key twice. You can also do this with your “If” and “try” Statements. You can also add your own Code Snippets if there are chunks of code that you often use and don’t want to type in full each time.

Go to http://msdn.microsoft.com/en-us/library/ms165392.aspx  to learn more about this.

Sunday, September 9, 2012

C# accessing or copying files over a network that requires authentication




I was working on a project with the requirement that I copy files over a network connection that needed username and password  authentication. The big problem that I found was that the .NET framework did not natively expose the win32 API needed to do this, so I had to write my own wrapper using P/Invoke.

You can learn more about P/Invoke on MSDN or check out the pinvoke.net wiki for tons of great resources.

Here is the class
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.ComponentModel;  
 using System.Runtime.InteropServices;  
 using System.Security.Principal;  
 namespace MyAppName  
 {  
 Public class SoddingNetworkAuth : IDisposable  
   {  
         [DllImport("advapi32.dll", SetLastError=true)]  
 Private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);  
     [DllImport("kernel32", SetLastError = true )]  
 Privatestaticexternbool CloseHandle(IntPtr hObject);  
 Private IntPtr userHandle = IntPtr.Zero;  
 Private WindowsImpersonationContext impersonationContext;  
 Public SoddingNetworkAuth(string user, string domain, string password)  
     {  
 if ( ! string.IsNullOrEmpty( user ) )  
         {  
 // Call LogonUser to get a token for the user  
 Bool loggedOn = LogonUser( user, domain, password,  
                 9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,  
                 3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,  
 Out userHandle );  
 if ( !loggedOn )  
 throw new Win32Exception( Marshal.GetLastWin32Error() );  
 // Begin impersonating the user  
 impersonationContext = WindowsIdentity.Impersonate( userHandle );  
         }  
     }  
 Public void Dispose()  
     {  
 if ( userHandle != IntPtr.Zero )  
 CloseHandle(userHandle );  
 if ( impersonationContext != null )  
 impersonationContext.Undo();  
     }  
   }  
 }  

Then you consume the class as follows
 using (new SoddingNetworkAuth(@"UserName", @"ServerName", @"Password"))  
 {  
      //Do something  
 }  

It’s that easy!

Let me know if this class helped or even if I just got you pointed in the right direction to solve your own unique problem.

Saturday, September 1, 2012

A New Job and A New Focus


I would like to start by apologizing for not posting on this blog for such a long time, I have just started a new job in a new city and I’ve been hellishly busy as a result.

The New Job


This all happened because I was getting complacent at my old job, having been there for 13 years, and was not growing as a developer. At the same time, I was suddenly inundated with recruiters desperate for a senior software developer. At first I was just going to interviews to find out what was available and how it compared, but I soon realized that I had fallen behind on the technology that people are using for software development. 

As a self taught developer, I have been wanting a mentor to help me grow my skills to become a better developer for a long time. I was also a jack of all trades in my old job; handling SEO, documentation, support, and project management over and above software development. So when I found a great development orientated company that didn’t care about my lack of qualification, and people that I really clicked with, I decided to jump at the opportunity.

The new job was in another city, but I have family there so, at the risk of sounding like a Will Smith song, I packed my bags and moved in with my Aunt and Uncle in Durban, and that's the story of how my life got turned upside down, and I became a senior developer at my new job.

The New Focus


What this all means for you dear reader, is that I will be changing the focus of this blog to deal primarily with C# and ASP.NET development. I will still leave my old SEO post up, but I really can be bother with trying to keep up will all of Google’s changes and new Metrics.

I would also like to take this opportunity to encourage you to take a look at your career and ask yourself if you have gotten stuck in a rut because you are just too comfortable. Are you still learning and growing, or have you allowed yourself to get into a dull routine?

Monday, July 23, 2012

C# Get Primary ID Key on SQL Insert

 

How do I get the primary ID key on SQL Insert in C#

If you need to get the auto-generated Primary Key of a newly added record when inserting into SQL server, it can be a nightmare. Some people try to use timestamps and unique data to look up the record in a new query, but you don’t need to do all that.

Update: I have different post for how to Get the Primary Key on insert using Entity Framework. Click here

scope_identity()

Lucky for us there is a wonderful SQL tool called scope_identity()

You can Google it if you want all the gory details. More importantly, here is a basic code example to get you going.

Code Sample;

1:        Int32 newProdID = 0;  
2:        string strSQL = "Insert into Table (Field1, Field2) values (@Field1, @Field2); "  
3:        strSQL += "SELECT CAST(scope_identity() AS int)";  
4:        SqlConnection conn = new SqlConnection(sConn);  
5:        try  
6:        {  
7:          conn.Open();  
8:          using (SqlCommand comd = new SqlCommand(strSQL, conn))  
9:          {  
10:            comd.Parameters.Add("@Field1", SqlDbType.VarChar);  
11:            comd.Parameters["@Field1"].Value = "some data";  
12:            comd.Parameters.Add("@Field2", SqlDbType.VarChar);  
13:            comd.Parameters["@Field2"].Value = "some data";  
14:            newProdID = (Int32)comd.ExecuteScalar();  
15:          }  
16:          conn.Close();  
17:        }  
18:        catch (Exception err)  
19:        { }  

If you want to streamline your work you can update your database in a method and return the Primary Key ID as an integer.

Code Block formated by codeformatter.blogspot.com

Thursday, March 29, 2012

Create .sln file for ASP.NET


How to create a .sln file for an existing ASP.NET application

  • From the Visual Studio menu choose "File | New | Project..."
  • From the resulting dialog, under "Other Project Types" choose "Visual Studio Solutions" and create a blank solution.
  • Then from the Visual Studio menu choose "File | Add | Existing Web Site" and point it to your web site to add it to your new solution.

It’s that simple