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

Thursday, May 30, 2013

Getting column value - Bad vs. Good Linq to Sql

Bad
int mainDepID = db.Departments.SingleOrDefault(y => y.ID == depID).MainDepartmentID;

Good
int mainDepID = 0;

Web.Model.Department currentDepartment = db.Departments.SingleOrDefault(y => y.ID == depID);

if (currentDepartment != null)
{
   mainDepID = currentDepartment.MainDepartmentID;
}

Thursday, May 23, 2013

ValidateAntiForgeryToken with postback and json in MVC

ValidateAntiForgeryToken as explained here from Stack Overflow
"MVC's Anti-Forgery Token support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.
It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form.
The feature doesn't prevent any other type of data forgery or tampering based attacks." 
To use this feature in MVC, you need to add the [HttpPostAuthorizeValidateAntiForgeryToken] attribute to your HttpPost methods.
Example:

[HttpPostAuthorizeValidateAntiForgeryToken]
public ActionResult MyPostBackMethod(string MyTextInputstring MyDropDown){
   //Do some stuff
}

In your view, you also need to add the following, if we are speaking Razor 
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @*Some HTML*@
}

Now, if we have some client side scripts, this will not work as the HttpPost method is expecting to use the ValidateAntiForgeryToken attribute.

What we need to do is simply add the following value to our json response

__RequestVerificationToken: $('[name=__RequestVerificationToken]').val()

Example:
<script type="text/javascript">
        var data = {
            MyTextInput: $('#txbMyTextInput' + id).val(),
            MyDropDown: $('#cbMyDropDown' + id).is(':checked'),
            __RequestVerificationToken: $('[name=__RequestVerificationToken]').val()
        };
 
        $.post('MyPostBackMethod', data,
        function (result) {
           //do something with result
        }, 'json');
<script />
There is no need to add any parameters on our method on the server side.


Wednesday, March 27, 2013

Validating Linq to Sql Model

If you have created a Linq to Sql class as your model and need to add validation to it, simply create an interface and add the columns needed to validate.

ILog interface class:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
 
namespace Test1.Models
{
    interface ILog
    {
        [Required]
        [RegularExpression(@"(\s|.){1,50}$", ErrorMessage = "Field cannot contain more than 50 characters")]
        string Name { getset; }
 
        [Required]
        [RegularExpression(@"[0-9]*", ErrorMessage = "Field must be an integer")]
        int TableKey { getset; }
 
        [Required]
        [RegularExpression(@"(\s|.){1,50}$", ErrorMessage = "Field cannot contain more than 500 characters")]
        string Value { getset; }
    }
}



Log LinqToSql class:

using Test1.Models;
using System.ComponentModel.DataAnnotations;
 
namespace Log.Model
{
    [MetadataType(typeof(ILog))]
    partial class Log : ILog
    {
    }
}

Simple enough?

For larger models, I suggest creating a ViewModel and handle everything in there...

Friday, January 4, 2013

Microsoft Lync in C#.NET

Microsoft.Lync namespace provides great way of rolling out your own custom Lync client.

I was faced with the problem on how to provide a messaging system in an enterprise software that we were creating. Seeing how well Lync worked with all its functionallities and the ability to save history into Outlook folder, I decided to build my own Lync client.

Below are pieces of code to get going with Lync... and as you will see, I am using most of the object except to provide the user with a interactive chat window. What is being done is that user or an application can provide a message to send, and the Lync application will trigger the local Lync client installed on the computer and pass in the message.


To start, we need to check if Lync client is running on the local machine:

try

            {

                _lyncClient = LyncClient.GetClient();

                return true;

            }

            catch (ClientNotFoundException ex)

            {

                MessageBox.Show(ex.ToString());

                return false;

            }

            catch (TypeInitializationException ex)

            {

                MessageBox.Show(ex.ToString());

                return false;

            }

            catch (NotStartedByUserException ex)

            {

                MessageBox.Show(ex.ToString());

                return false;

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString());

                return false;

            }


We can then wire up events and check the sign in status of the client. If the client is signed out, we can sign in the client:

if (_lyncClient != null)

            {

                _lyncClient.StateChanged += new EventHandler<ClientStateChangedEventArgs>

                (LyncClient_StateChanged);

 

                // Check if Lync is signed in

                if (_lyncClient.State != ClientState.SignedIn)

                {

                    _lyncClient.BeginSignIn(null, null, null, result =>

                    {

                        if (result.IsCompleted)

                        {

                            _lyncClient.EndSignIn(result);

                            InitializeClient(); // Setup application logic

                        }

                        else

                        {

                            MessageBox.Show("Could not sign in to Lync.");

                        }

                    }

                            , "Local user signing in" as object);

                }

                else

                {

                    // Set up ConversationManager, ContactManager, and Self objects

                    // Wire up events

                    // Subscribe to events on my contacts

                    IsLyncSignedIn = true;

                    InitializeClient();

                }

            }

 
At this point, we are good to go to grab some Lync objects:
 
//Initialize Lync client
        void InitializeClient()
        {
            if (_lyncClient == null)
                _lyncClient = Microsoft.Lync.Model.LyncClient.GetClient();
 
            _conversationManager = _lyncClient.ConversationManager;
            _contactManager = _lyncClient.ContactManager;
            _self = _lyncClient.Self;
            _automation = LyncClient.GetAutomation();
 
            try
            {
                //Load all contacts
                this.ListContacts();
            }
            catch (Exception)
            {
                throw new Exception("Initialization exception.");
            }
        }
 Not so hard, ey?
So the last item remains... how do we send a message? In this case, we want to send a message to the user that a particular order belongs to from our enterprise system, so we grab their email and plug it into our Lync client together with a message:

//Send Message to selected user
        public static void SendIM(String _selectedUser, String _messageText)
        {
            try
            {
                //if ((string)SelectedDataRow[0] != null)
                if (_selectedUser != "")
                {
                    if (_messageText != String.Empty)
                    {
                        //This is shared method need this to allow automation
                        Automation automation = LyncClient.GetAutomation();
 
                        //Add two URIs to the list of IM addresses.
                        List<string> inviteeList = new List<string>();
                        inviteeList.Add(_selectedUser);
                        //inviteeList.Add(ConfigurationManager.AppSettings["CallingUserURI"]);
                        //inviteeList.Add(ConfigurationManager.AppSettings["UserURI2"]);
 
                        //Specify IM settings.
                        Dictionary<AutomationModalitySettings, object> mSettings = new Dictionary<AutomationModalitySettings, object>();
                        string messageText = _messageText;
                        mSettings.Add(AutomationModalitySettings.FirstInstantMessage, messageText);
                        mSettings.Add(AutomationModalitySettings.SendFirstInstantMessageImmediately, true);
 
                        //Broadcast the IM messages.
                        IAsyncResult ar = automation.BeginStartConversation(AutomationModalities.InstantMessage, inviteeList, mSettings, null, null);
                        csWindow = automation.EndStartConversation(ar);
                        //AutoResetEvent completedEvent = new AutoResetEvent(false);
                        //completedEvent.WaitOne();
                        //completedEvent.Set();
                    }
                    else
                    {
                        MessageBox.Show("You must enter a message");
                    }
                }
                else
                {
                    MessageBox.Show("You must enter a valid email");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Exception");
            }
        }
 
Thats it.
Remember that this is only part of the fun. You can implement almost all the features of Lync into your custom application such as screen sharing, file transfer and more...

RelayCommand Class for MVVM - C# and VB

Publishing both C# and VB version of the RelayCommand by Josh Smith


Namespace ApplicationClass

''' <summary>

''' A command whose sole purpose is to

''' relay its functionality to other

''' objects by invoking delegates. The

''' default return value for the CanExecute

''' method is 'true'.

''' </summary>

''' <remarks>Class taken from online example. http://msdn.microsoft.com/en-us/magazine/dd419663.aspx Josh Smith</remarks>

Public Class RelayCommand

Implements ICommand

#Region "Fields"

Private ReadOnly _execute As Action(Of Object)

Private ReadOnly _canExecute As Predicate(Of Object)

#End Region

#Region "Constructors"

''' <summary>

''' Creates a new command that can always execute.

''' </summary>

''' <param name="execute">The execution logic.</param>

Public Sub New(ByVal execute As Action(Of Object))

Me.New(execute, Nothing)

End Sub

''' <summary>

''' Creates a new command.

''' </summary>

''' <param name="execute">The execution logic.</param>

''' <param name="canExecute">The execution status logic.</param>

Public Sub New(ByVal execute As Action(Of Object), ByVal canExecute As Predicate(Of Object))

If execute Is Nothing Then

Throw New ArgumentNullException("execute")

End If

_execute = execute

_canExecute = canExecute

End Sub

#End Region

#Region "ICommand Members"

'<DebuggerStepThrough()> _

Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute

Return If(_canExecute Is Nothing, True, _canExecute(parameter))

End Function

Public Custom Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged

AddHandler(ByVal value As EventHandler)

AddHandler CommandManager.RequerySuggested, value

End AddHandler

RemoveHandler(ByVal value As EventHandler)

RemoveHandler CommandManager.RequerySuggested, value

End RemoveHandler

RaiseEvent(ByVal sender As System.Object, ByVal e As System.EventArgs)

End RaiseEvent

End Event

Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute

_execute(parameter)

End Sub

#End Region

End Class

End Namespace











using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows.Input;

namespace Xpert_Lync.ViewModel

{

public class RelayCommand : ICommand

{

#region Fields

readonly Action<object> _execute;

readonly Predicate<object> _canExecute;

#endregion // Fields

#region Constructors

public RelayCommand(Action<object> execute)

: this(execute, null)

{

}

public RelayCommand(Action<object> execute, Predicate<object> canExecute)

{

if (execute == null)

throw new ArgumentNullException("execute");

_execute = execute;

_canExecute = canExecute;

}

#endregion // Constructors

#region ICommand Members

 

public bool CanExecute(object parameter)

{

return _canExecute == null ? true : _canExecute(parameter);

}

public event EventHandler CanExecuteChanged

{

add { CommandManager.RequerySuggested += value; }

remove { CommandManager.RequerySuggested -= value; }

}

public void Execute(object parameter)

{

_execute(parameter);

}

#endregion // ICommand Members

}

}