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 21, 2012

JavaScript SecondIndexOf or (x)indexOf

The JavaScript indexOf() and lastIndexOf() methods return the position of the first and last occurrence of a specified value in a string

You can learn more about them here

These can be very usefull, but what if you want the Second indexOf() to get the second occurrence of a specified value in a string. There is no standard JavaScript method for this, so I made my own one;

 function SecondIndexOf(Val, Str)  
 {  
   var Fst = Str.indexOf(Val);  
   var Snd = Str.indexOf(Val, Fst+1)  
   return Snd  
 }  

But why stop there, what if you want the third or fourth indexOf()
The following function lets you specify which occurrence of the specified value to find in the string;

 function xIndexOf(Val, Str, x)  
 {  
   if (x <= (Str.split(Val).length - 1)) {  
     Ot = Str.indexOf(Val);  
     if (x > 1) { for (var i = 1; i < x; i++) { var Ot = Str.indexOf(Val, Ot + 1) } }  
     return Ot;  
   } else { alert(Val + " Occurs less than " + x + " times"); return 0 }  
 }  

Here is an egsample of how you can use this;

   var PicPath = "/somedirectory/pics/";  
   var AppPath = picpath.substring(0, xIndexOf('/', PicPath, 2) + 1);  

Let me know if you found this usefull, or can recommend any enchancments.

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 16, 2012

JavaScript Error – Submit is not a Function


If you get the JavaScript error “Submit is not a Function” then you are probably trying to call the Form’s Submit() Method, but you also have a button whitch is called Submit. This results in a conflict in the JavaScript becuse the Submit Method is already bound to the button.

The Solution is simply to change the name of the button so that name=”newname” (or what ever you prefer).

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.