I LOVE C#

Eyal Vardi

Experts4D

  • Eyal Vard

Firefox Extensions

Post News

January 2006 - Posts

New Code Snippets for C#
 * Application Code Snippets
    * Collections and Arrays Code Snippets
    * Connectivity Code Snippets
    * Crystal Reports Code Snippets
    * Database Code Snippets
    * Datatypes Code Snippets
    * File System Code Snippets
    * Math Code Snippets
    * Operating System Code Snippets
    * Security Code Snippets
    * Smart Devices Code Snippets
    * Windows Forms Code Snippets
    * XML Code Snippets
To download code snippets for all the categories and retain the directory install structure of these snippets, click here.
Tool for write Snippets click here.
Useful Tip in ASP.NET 2.0
How to add additional drop-down values to DropDownList,
such as an initial "(Select a State)" value,
that are not part of the databound result
?
Please read Scott Guthrie blog.
Posted: Jan 30 2006, 02:20 AM by Vardi | with no comments
Filed under:
Web Resource cool new feature in ASP.NET 2.0

See http://msdn2.microsoft.com/system.web.ui.webresourceattribute.aspx.

Very useful when you want to add java script or any resource to your custom control.

 

Posted: Jan 29 2006, 02:17 PM by Vardi | with 23 comment(s)
Filed under:
Building XML editor in .NET 2.0

Thanks to Hannes Preishuber  feedback,
I found how to write it with WebBrowser control (C# version)

object
obj = webBrowser1.ActiveXInstance;
HtmlDocument hd = webBrowser1.Document;
IHTMLDocument2 axObj = hd.DomDocument as IHTMLDocument2;
axObj.designMode = "On";

 

Posted: Jan 28 2006, 02:11 PM by Vardi | with 36 comment(s) |
Filed under:
Building XML Editor

Step 1: Open win forms

Step 2: Add reference to Microsoft Web Browser (COM)

Step 3: Add the Code to the forms

IHTMLDocument2 doc;
axWebBrowser1.Navigate(“
http://msdn.microsoft.com/”);
axWebBrowser1.PutProperty(
"EditMode" ,true );
object boxDoc = axWebBrowser1.Document;
doc = (IHTMLDocument2)boxDoc;
doc.designMode = "On";

I didn’t Find this property in the new WebBrowser control,
so I go back to the COM Component

Posted: Jan 28 2006, 05:41 AM by Vardi | with 2 comment(s)
Filed under:
Dynamic role management ( by context ).

Same time we need dynamic role management ( by context ).

We can derive from SqlRoleProvider and override is methods.

Step 1: Build your role provider

public class MySqlRoleProvider : SqlRoleProvider 
{
	public override string[] GetRolesForUser( string username )
	{
		string[] result = base.GetRolesForUser( username );
		// TODO: your implementation.......
// Example: <New Role Name>=”<Old Role Name>+<Context:Acount ID>” return result; } // TODO: Override other methods }
Step 2:Add the role provider to the config file

<roleManager enabled="true"

defaultProvider="AspNetSqlRoleProvider">

<providers>

<clear/>

<add name="AspNetSqlRoleProvider"

connectionStringName="DataBaseName"

applicationName="/Demo1"

type="MySqlRoleProvider" />

</providers>

</roleManager>

Step 3: Build Dynamic Role Permission Attribute

// Use the command line option '/keyfile' or appropriate project settings to sign this assembly.

[assembly: System.Security.AllowPartiallyTrustedCallersAttribute()][AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly , AllowMultiple = true , Inherited = false )]

[Serializable]

public class DynamicRolePermissionAttribute : CodeAccessSecurityAttribute

{

SecurityAction action;

string m_Role;

public DynamicRolePermissionAttribute( SecurityAction action )

: base( action )

{

this.action = action;

}

public override IPermission CreatePermission ()

{

PrincipalPermission p =

new PrincipalPermission( null , Role + Context:Acount ID" );

return p;

}

public string Role

{

get{return m_Role;}

set{m_Role = value;}

}

}

Step 4: Declarative Secure Component

public class DeclarativeSecureComponent

{

[PrincipalPermission( SecurityAction.Demand ,

Role = "DistrictManagers" )]

public static void DistrictManagerMethod()

{

//TODO:

}


[
DynamicRolePermission( SecurityAction.Demand ,

Role = "RegionalManagers" )]

public static void RegionalManagerMethod()

{

//TODO:

}

}

 

Step 5: Test the code…

 

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Test my Role Provider</title>

<script language="C#" runat="server">

protected void btnDistrictManager_Click( object sender , EventArgs e )

{

DeclarativeSecureComponent.DistrictManagerMethod();

lblResult.Text = "The user is District Manager";

}

protected void btnRegionalManager_Click( object sender , EventArgs e )

{

DeclarativeSecureComponent.RegionalManagerMethod();

lblResult.Text = "The user is Regional Manager";

}

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:LoginName ID="LoginName1" runat="server" />

<asp:LoginStatus ID="LoginStatus1" runat="server" />

<br />

<br />

<asp:Button ID="btnDistrictManager" runat="server"

OnClick="btnDistrictManager_Click"

Text="District Manager" Width="155px" /><br />

<br />

<asp:Button ID="btnRegionalManager" runat="server"

OnClick="btnRegionalManager_Click"

Text="Regional Manager" />

<br />

<br />

<asp:Label ID="lblResult" runat="server"

Height="135px" Width="514px">

</asp:Label>

</div>

</form>

</body>

</html>

 

Membership and Role Providers in ASP.NET 2.0

Very nice article by scott

The extensible provider model in ASP.NET 2.0 implements features we’ve all needed for out applications over the years – like membership and role management. In this article we will concentrate on role providers.

Useful attributes for working with ObjectDataSource

1. DataObjectAttribute

Use the DataObjectAttribute attribute to identify an object as suitable for use by an ObjectDataSource object. Design-time classes such as the ObjectDataSourceDesigner class use the DataObjectAttribute attribute to present suitable objects to bind to an ObjectDataSource object.

2. DataObjectMethodAttribute

You can use the DataObjectMethodAttribute to identify data operation methods on a type marked with the DataObjectAttribute attribute so that they are more easily identified by callers using reflection. When the DataObjectMethodAttribute attribute is applied to a method, it describes the type of operation the method performs and indicates whether the method is the default data operation method of a type

Example:

[DataObjectAttribute]

public class NorthwindData

  public NorthwindData() {}

  [DataObjectMethodAttribute(DataObjectMethodType.Select, true)]
  public static IEnumerable GetAllEmployees()
  {
       AccessDataSource ads = new AccessDataSource();
      ads.DataSourceMode = SqlDataSourceMode.DataReader;
      ads.DataFile = "~//App_Data//Northwind.mdb";
      ads.SelectCommand = "SELECT EmployeeID,FirstName,LastName FROM Employees";
      return ads.Select(DataSourceSelectArguments.Empty);
  }

  [DataObjectMethodAttribute(DataObjectMethodType.Delete, true)]
  public void DeleteEmployeeByID(int employeeID)
  {
       throw new Exception("The value passed to the delete method is " + employeeID.ToString());
  }
}

 

éåí ùéùé îùôçúé
אני אחותו של אייל מנסה את כוחי בכתיבה ראשונה בבלוג רציתי לספר לכם שכול יום שישי אנחנו 

נפגשים כל המשפחה לארוחת ערב חגיגית וכל אחד מהבאים מספר את שעבר אליו בשבוע החולף דבר
שעוזר ושומר את כולנו בתמונה המשותפת של החיים ושל המשפחה אני חייבת להיות גלויה ולהגיד שלא
קל לנו להבין את כל הרעיונות של איל אבל אנחנו מנסים המוח שלו עובד בקצב מאוד מהיר ואני מקווה
שאום מבינים מה שהוא כותב בכול אופן כולנו מבינים שמדובר כאן ביצור מוזר מכוכב אחר
יש לי עוד אח יותר קטן והוא סטודנט במרכז הבין תחומי בהרצליה ,לא היה לו מה לספר לנו חדש השבוע 
ואני אחות שלהם לי יש זכיון של מיכל נגרין בכפר סבא ובמידה ובאמת משהוא קורא 
את הבלוג הזה כמו שאיל אומר אתם מוזמנים לבוא ולהגיד לי שאתם  הקוראים 
ואני מבטיחה לכם הנחה שמי הילה ורדי היה נחמד וסוף שבוע טוב לכולנו 
ביי

Add Action List to Control
ActionlistStep 1 : Build the control
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomDesignerActionsDemo
{
	[DefaultProperty( "Text" )]
	[ToolboxData( "<{0}:UserInfo runat=server>" )]
	[Designer( typeof( MyDesigner ) )]
	public class UserInfo : WebControl
	{
		#region Fields
		private int m_Age;
		protected TextBox txbAge;
		[CategoryAttribute( "Misc" )]
		[DescriptionAttribute( "My Age" )]
		public int Age
		{
			get
			{
				return m_Age;
			}
			set
			{
				m_Age = value;
			}
		}

		private string m_Email;
		protected TextBox txbEmail;
		[CategoryAttribute( "Misc" )]
		[DescriptionAttribute( "My Email" )]
		public string Email
		{
			get
			{
				return m_Email;
			}
			set
			{
				m_Email = value;
			}
		}

		private DateTime m_Date;
		protected TextBox txbDate;
		[CategoryAttribute( "Misc" )]
		[DescriptionAttribute( "My Date" )]
		public DateTime Date
		{
			get
			{
				return m_Date;
			}
			set
			{
				m_Date = value;
			}
		}

		private CityList m_City;
		protected TextBox txbCity;
		[CategoryAttribute( "General" )]
		[DescriptionAttribute( "My City" )]
		public CityList City
		{
			get
			{
				return m_City;
			}
			set
			{
				m_City = value;
			}
		}

		[Bindable( true )]
		[Category( "Appearance" )]
		[DefaultValue( "" )]
		[Localizable( true )]
		public string Text
		{
			get
			{
				String s = (String)ViewState[ "Text" ];
				return ( ( s == null ) ? String.Empty : s );
			}

			set
			{
				ViewState[ "Text" ] = value;
			}
		}
		#endregion	

		bool IsCreateChildControls = false;

		protected void SetValueInTextBox()
		{
			txbAge.Text = Age.ToString();
			txbCity.Text = City.ToString();
			txbDate.Text = Date.ToString();
			txbEmail.Text = Email;
		}
		protected override void EnsureChildControls()
		{
			if ( !IsCreateChildControls )
				CreateChildControls();

			base.EnsureChildControls();
		}
		protected override void CreateChildControls()
		{
			txbAge	 = new TextBox();
			txbCity  = new TextBox();
			txbDate  = new TextBox();
			txbEmail = new TextBox();
			base.CreateChildControls();

			IsCreateChildControls = true;
		}
		protected override void RenderContents( HtmlTextWriter output )
		{
			EnsureChildControls();
			SetValueInTextBox();
			output.Write( Text );

			output.Write( "
City: " ); txbCity.RenderControl( output ); output.Write( "
Age: " ); txbAge.RenderControl( output ); output.Write( "
Date: " ); txbDate.RenderControl( output ); output.Write( "
Email: " ); txbEmail.RenderControl( output ); } } }
Step 2 : Build the designer for the control
using System;
using System.Collections.Generic;
using System.Web.UI.Design;
using System.ComponentModel.Design;



namespace CustomDesignerActionsDemo
{
	public class MyDesigner : ControlDesigner
	{
		private DesignerActionListCollection al = null;

		public override DesignerActionListCollection ActionLists
		{
			get
			{
				if ( al == null )
				{
					al = new DesignerActionListCollection();
					al.AddRange( base.ActionLists );

					// Add a custom DesignerActionList
					al.Add( new MyDesignerActionList( this ) );
				}
				return al;

			}
		}
	}
}

Step 3 : Build the action list for the designer
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace CustomDesignerActionsDemo
{
	public class MyDesignerActionList : DesignerActionList
	{
		MyDesigner m_parent;

		public MyDesignerActionList( MyDesigner parent )
			: base(parent.Component)
		{
			m_parent = parent;
		}

		public override DesignerActionItemCollection GetSortedActionItems()
		{
			// Create list to store designer action items
			DesignerActionItemCollection actionItems = new DesignerActionItemCollection();

			// Add Appearance category header text
			actionItems.Add(new DesignerActionHeaderItem("Misc"));

			//// Add Appearance category descriptive label
			actionItems.Add(
			  new DesignerActionTextItem(
				"Properties that affect how the User looks." ,
				"Misc" ) );

			//// Add Email designer action property item
			actionItems.Add(
			  new DesignerActionPropertyItem(
				"Email" ,
				"Email" ,
				GetCategory( this.WebControl , "Email" ) ,
				GetDescription( this.WebControl , "Email" ) ) );

			actionItems.Add(
			  new DesignerActionPropertyItem(
				"Age" ,
				"Age" ,
				GetCategory( this.WebControl , "Age" ) ,
				GetDescription( this.WebControl , "Age" ) ) );

			actionItems.Add(
			  new DesignerActionPropertyItem(
				"Date" ,
				"Date" ,
				GetCategory( this.WebControl , "Date" ) ,
				GetDescription( this.WebControl , "Date" ) ) );

			actionItems.Add(
			  new DesignerActionPropertyItem(
				"City" ,
				"City" ,
				GetCategory( this.WebControl , "City" ) ,
				GetDescription( this.WebControl , "City" ) ) );

			actionItems.Add(
				new DesignerActionMethodItem(
				this ,
				"ClearValues" ,
				"Clear Values" ,
				true ) ); // for the Propeties wondows

			return actionItems;
		}

		#region Control Proxy Properties
		public string Email
		{
			get	{ return WebControl.Email; }
			set { SetProperty( "Email" , value ); }
		}
		public int Age
		{
			get{return WebControl.Age;}
			set{SetProperty( "Age" , value );}
		}
		public DateTime Date
		{
			get{return WebControl.Date;	}
			set{SetProperty( "Date" , value );	}
		}
		public CityList City
		{
			get{return WebControl.City;}
			set{SetProperty( "City" , value );}
		}
		public void ClearValues()
		{
			SetProperty( "Email" , string.Empty );
			SetProperty( "Age" , -1 );
			SetProperty( "City" , CityList.Tel_Aviv );
			SetProperty( "Date" , DateTime.Now );
		}

		#endregion


		private UserInfo WebControl
		{
			get
			{
				return (UserInfo)this.Component;
			}
		}		

		private string GetCategory( object source , string propertyName )
		{
			PropertyInfo property       = source.GetType().GetProperty( propertyName );
			CategoryAttribute attribute = (CategoryAttribute)property.GetCustomAttributes( typeof( CategoryAttribute ) , false )[ 0 ];
			if ( attribute == null )
				return null;
			return attribute.Category;
		}		
		private string GetDescription( object source , string propertyName )
		{
			PropertyInfo property = source.GetType().GetProperty( propertyName );
			DescriptionAttribute attribute = (DescriptionAttribute)property.GetCustomAttributes( typeof( DescriptionAttribute ) , false )[ 0 ];
			if ( attribute == null )
				return null;
			return attribute.Description;
		}

		// Helper method to safely set a component’s property
		private void SetProperty( string propertyName , object value )
		{
			// Get property
			PropertyDescriptor property = TypeDescriptor.GetProperties( this.WebControl )[ propertyName ];
			// Set property value
			property.SetValue( this.WebControl , value );
		}
	}

	public enum CityList
	{
		Tel_Aviv, Ramat_Gan
	}
}
User info with Action List !!!!
Actionlist
More Posts Next page »