3/4/12

Send Email Using your default Outlook Account

 
Sometimes we can face smtp problems when we want to send an email via .NET code.Proxy Problem Or not using the right SMTP port.A more esay way is to use the interoperability  between outlook and visual studio framework.
With adding the Microsoft.Office.Interop reference to our project we can send an email with our default account of outlook.

      ---> 
Under a button Click put the code snippet below :
Imports Microsoft.Office.Interop
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesButton1.Click
Dim App As New Outlook.Application()
Dim email As Outlook.MailItem = DirectCast(App.CreateItem(Outlook.OlItemType.olMailItem), Outlook.MailItem)
email.Recipients.Add(TextBox1.Text)
email.Subject = "ur Subject"
email.Body = "ur Body"
Try
DirectCast(email, Outlook.MailItem).Send()
MsgBox("Email is sent to  " & TextBox1.Text & " Successfully", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox("Error!Check That your Outlook is open", MsgBoxStyle.Critical)
End Try
End Sub
End Class
The recipient is entered in a simple textbox but you can use combobox or checkedboxlist to put multi email:



You will find the mail directly inserted in the sent mail box of your outlook default account.
You can download the code from this Link

2/9/12

Error Crystal Report 13.0 in ASP.NET page

After installing Crystal Report 13.0 for Visual Studio 2010 from this link 

http://downloads.businessobjects.com/akdlm/cr4vs2010/CRforVS_13_0_2.exe   

and when you want to execute a page containing   Crystal Report Viewer's Control you may encounter the error saying CS0433: The type 'CrystalDecisions.Web.CrystalReportViewer' exists in both:' ......:




The cause is that that control references 2 differents versions of crystal report.So in your markup page you have :

<%@ Register Assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
    Namespace="CrystalDecisions.Web" TagPrefix="CR" %>

The version of the assembly is 10.5 and It's not coherent with crystal report 13.0 installed.

The solution is to replace that registry version with this one:

<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
    Namespace="CrystalDecisions.Web" TagPrefix="CR" %>

Passing values between two forms


There is frequently a need to pass a value between two Windows Forms. 
The code below provides an example of how this can be accomplished in Visual Basic .NET creating the property below in the form you wish to pass a value to.

Public Property passedVariable() As String
    Get
        Return nameform
    End Get
    Set(ByVal value As String)
        nameform = value
    End Set
End Property
Private nameform As String
Textbox1.Text=passedVariable

Once an instance of the form is created we can then assign the property the value we wish to pass into the form as show below.

    Dim f1 As New Form1
f1.passedVariable = "test"

The result will be that the textbox1 in form1 will show test. 

Get Physical Name of an ASP Page from a URL

Sometimes we need to get the physical name (from the bar adress of url) of an asp.net page to pass it by value or to loop throw project pages programmatically.


In that purpose we use a function to split the URL's string 

Public Function cutString(ByVal url As StringAs String
 
      Dim St1() As String
      St1 = Split(url, "/")
 
      For i = 0 To UBound(St1)
          cutString = St1(i)
      Next i
      cutString = St1(UBound(St1))
  End Function

and then get the whole Url and use our function that extract just the name of the page with its extension(.aspx)


Protected Sub Page_Load(ByVal sender As ObjectByVal As System.EventArgs) Handles Me.Load
  
Textbox1.Text=  cutString(Request.Url.ToString)
End Sub

Authentification in ASP.NET Animated with a Progress Bar

Its an easy way in order to login into webpages using the login control in asp.net and the membership provider animated with a progress bar.

In the Parsing Xml side, we add a login control and an update progress bar


<asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel id="UpdatePanel1" runat="server">
     <contenttemplate>
        <asp:Login ID="Login1" runat="server"
         
            style="Z-INDEX: 110; LEFT: 350px; POSITION: absolute; TOP: 100px"
            BackColor="White" BorderColor="#F1F6FE" BorderPadding="4" BorderStyle="Solid"
            BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#333333"
            Height="140px" Width="340px"
      UserNameLabelText="ID:" DestinationPageUrl="Welcome.aspx">
       
      <LoginButtonStyle BackColor="White" BorderColor="#41519A" BorderStyle="Solid"BorderWidth="1px"
        Font-Size="0.8em" ForeColor="#41519A" />
    <TextBoxStyle Font-Size="0.8em" />
    <TitleTextStyle BackColor="#2153AA" Font-Bold="True" Font-Size="0.8em" ForeColor="White" />
    <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
    </asp:Login>
</contenttemplate>
</asp:UpdatePanel>
         
<asp:UpdateProgress ID="UpdateProgress1" runat="server" >
            <ProgressTemplate>
                 <img src="images/loadingAnim.gif"  style="Z-INDEX: 110; LEFT: 400px; POSITION: absolute; TOP: 300px"/>
            </ProgressTemplate>
        </asp:UpdateProgress>


In the code behind using vb.net we use the membership provider generated by the visual studio to securise our website.

We add a sleeping thread of 3 second in the event Login1_LoggingIn to let the progress bar show some animation.

Protected Sub Page_Load(ByVal sender As ObjectByVal As System.EventArgs) Handles Me.Load
       If Not Page.IsPostBack Then
           If Request.IsAuthenticated AndAlso NotString.IsNullOrEmpty(Request.QueryString("ReturnUrl")) Then
 
               Response.Redirect("~/NoAuthorized.aspx")
           End If
       End If
   End Sub
 
   Protected Sub Login1_Authenticate(ByVal sender As ObjectByVal AsSystem.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
 
       If Membership.ValidateUser(Login1.UserName, Login1.Password) Then
 
           Dim usrInfo As MembershipUser = Membership.GetUser(Login1.UserName)
 
           e.Authenticated = True
 
       Else
           e.Authenticated = False
       End If
   End Sub
 
   Protected Sub Login1_LoginError(ByVal sender As ObjectByVal As System.EventArgs) HandlesLogin1.LoginError
 
       Login1.FailureText = Resources.traduction.failureText
 
   End Sub
   Protected Sub Login1_LoggingIn(ByVal sender As ObjectByVal AsSystem.Web.UI.WebControls.LoginCancelEventArgs) Handles Login1.LoggingIn
       System.Threading.Thread.Sleep(3000)
   End Sub

ASP.NET Ajax Technology in New Version Browser (IE9)

Using an old version of Ajax can be not compatible with Internet Explorer 9.

i.e: problem with popup windows 

Adding the line below in a master page, for example, fixes that problem 


<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage"     %>
<meta http-equiv="X-UA-Compatible" content="IE=100" <!-- IE9 mode -->
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

How to Use a Membership Provider of ASP.NET in WINFORM Application

We can use the known membership provider of ASP.NET in our winform application.

What is the goal? The membership of ASP.NET is a really complete way to manage users and roles (Create,Edit,Delete, access rules to forms like access rules to pages ).

How do we implement it?

First we create a login form connecting to the database ASPDBNET.mdf (generated automatically in a project asp.net)

The code of the button login will be :

Imports System.Security.Principal
Imports System.Web.Security

Private
 Sub OK_Click(ByVal sender As System.ObjectByVal As System.EventArgs) Handles OK.Click
        If Membership.ValidateUser(UsernameTextBox.Text, PasswordTextBox.Text) Then
           '''' treatment if authenticated
     
        Else
             ''''
        End If
    End Sub

Same time we need to edit the app.config and to add under configuration 

<system.web>
    <membership defaultProvider="AspNetSqlMembershipProvider">
      <providers>
           <remove name=AspNetSqlMembershipProvider"/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider"connectionStringName="AspNetConnectionString" enablePasswordRetrieval="false"enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="AspNet"requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5"minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10"passwordStrengthRegularExpression=""/>
      </providers>
    </membership>
    <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider" cacheRolesInCookie="true"createPersistentCookie="false" cookieProtection="All">
      <providers>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"applicationName="AspNet" connectionStringName="AspNetConnectionString"/>
      </providers>
    </roleManager>
  </system.web>

Once authenticated and redirected to another winform we can detect current user and work on access rules by roles 


''' treatment for current user
nom = Thread.CurrentPrincipal.Identity.Name
        Dim user As MembershipUser = Membership.GetUser(nom)
        Dim identity As New GenericIdentity(user.UserName)
        Dim principal As New RolePrincipal(identity)
        Threading.Thread.CurrentPrincipal = principal
               If Roles.GetRolesForUser(nom).Length = 1 Then
            rolesArray = Roles.GetRolesForUser(nom)
            role = rolesArray.First.ToString
            ''' enable controls for examples for the role of current user
        Else '' disable controls
        End If
    


To create a user you can create a winform with simple textboxes (encryted one for the password) and use that code 

Imports System.Security.Principal
Imports System.Web.Security
Public Class AddUser
 
    Private Sub Button1_Click(ByVal sender As System.ObjectByVal As System.EventArgs) HandlesButton1.Click
        Dim user As MembershipUser
        user = Membership.CreateUser(TextBox1.Text, TextBox2.Text)
        MsgBox(TextBox1.Text & "is created successfully")
        Me.Dispose()
 
    End Sub
End Class