Use of resource files in asp.net

  • 2020-05-16 06:42:24
  • OfStack

Resources can be a wide range of elements, including interface elements that interact with the user (such as bitmaps, ICONS, or cursors), custom files for the data required by the application, and version files used to install API, menus, and dialogs. Add resources to the.Net assembly to achieve functions such as resource reuse. Visual Studio.Net integrated development environment IDE makes it easy to create resource files, add methods to projects, and add forms and libraries, except that you need to set the "BuildAction" property of the resource to "Embedded Resource" so that you can use the resource
Create a resource
String tables are a very common resource. There are two ways to create such a resource file:
(1) use.Net command line tool ResGen to create. Start by creating a text file that contains the content of the resource, which you can use (notepad, EditPlus, and other text editors). The text file consists of the required "key-value pairs" whose names can be referenced in the program and whose string values can be assigned after the key name is set to complete the creation of the file. As an example, the following statement fragment generates such a resource, saved as userinfo.txt in the following format:

 
Username="Songh"; 
Sex="Boy"; 
Birthday="1973-01-15"; 
Salary="5000RMB"; 

The text file is then converted to a resource file, again via the ResGen tool. Execute the following statement: ResGen userinfo.txt, and the resource file userinfo.resources will be generated. In addition, ResGen can create a.resX resource file based on the XML format. By executing the following command, ResGen userinfo.resources userinfo.resx will generate userinfo.resx in the Xml format. However, the ResGen tool does not support manipulation of image resources, and the following methods do not have such limitations.
(2) use the ResourceWriter class. To make it easy to create resource files, the.Net structure provides the ResourceWriter class to support the creation of various resource types such as images. The ResourceWriter class contains methods that write resources to output files or output streams in the system's default format. Unlike method 1), this is done in one process.
To create a resource file, call the constructor of the ResourceWriter class to initialize the class instance and provide at least the stream name or file name. The actual content of the resource is done by calling the AddResource method, which specifies the resource as a name and value pair. The actual writing of the resource is done by calling the Generate method, but the Generate method is implicitly called when the Close method is called to close the ResourceWriter.
The ResourceWriter.AddResource () method adds a resource to the list of resources to write to. After creating an instance of the ResourceWriter class, this method can add up to 2GB resources. The following overloaded method 1 is used to add string resources to the list of resources:
 
public void AddResource( 
string name,// Key name  
string value// value  
); 

Here, the first parameter of the AddResource method specifies the key name and the second parameter specifies the value. This method is called multiple times to complete the creation of the string table. In addition, adding image resources can be done by instantiating the class Image (at this point, add the System.Drawing namespace).
The following code snippet generates the resource file userinfo.resources that contains the string table and image.
 
using System; 
using System.Resources; 
using System.Drawing; 
public class RS 
{ 
public static void Main() 
{ 
ResourceWriter rw=new 
ResourceWriter("userinfo.resources");// Provide the file name for initialization ResourceWriter The class instance.  
Image image=Image.FromFile("photo.gif") ; // instantiation Image class  
rw.AddResource("Photo",image);// Add an image  
rw.AddResource("Username","songh");// Add string  
rw.AddResource("Sex","boy");// Add string  
rw.AddResource("Birthday","1973-01-15");// Add string  
rw.AddResource("Salary","5000RMB");// Add string  
rw.Close();// Shut down ResourceWriter And implicitly called Generate() Method completes the resource file writing to the disk file.  
} 
} 

The above code first opens the graphics file photo.gif and creates an Image object. To do so, the graphics file must either exist in the directory of the project executable (usually the project's \Bin\Debug directory) or specify the full path to the image in the method parameter of Image.FromFile (). The string resource is then added to the ResourceWriter object through several calls to the AddResouce() method. Finally, the Close() method is called to close the ResourceWriter object and implicitly calls the Generate() method to write the resource to the file userinfo.resources.
Compiling the above code and running it will create the resource file userinfo.resources.
The resource file generated in either of these ways can be added to the assembly as an external file, or embedded in Dll or exe. The following continues to show how to use resource files in the Windows application.
Working with resource files
You can easily add resource files to the assembly using Visual Studio.Net integrated development environment IDE. Simply add an existing resource file to the project you created and simply set its properties to embed the resource file into the assembly. The following illustrates any use of the userinfo.resources resource file created above with an C# Windows console instance.
First, create C# Windows Console project ResourceUserinfo, open "project \ add existing items", find the previously created resource file Userinfo.resources to add to the project;
Then, select the resource file and set the property BuildAction (build operation) to Embedded (embedded resource) so that the resource file can be embedded in the output assembly.
Now you can use the resource file. The ResourceManager class in the System.Resources namespace provides easy access to specific resources at run time. This can be done specifically through the GetObject and GetString methods, where the corresponding value is returned as a parameter with the key name.
The constructor of the ResourceManager class initializes a new instance of the ResourceManager class, and its overloaded method 1 looks for resources contained in files that are exported from the specified root name using the given Assembly.
 
public ResourceManager( 
string baseName, 
Assembly assembly 
) 

Where the parameter baseName represents the root name of the resource. The root name consists of the application namespace and the resource file name (without an extension). Thus, the root name of the resource in this example should be: UserinfoResource.Userinfo, which can also be programmatically obtained by calling the GetManifestResourceNames() method.
The other parameter, assembly, represents the current main assembly, which in this case is actually the assembly being executed. An easy way to get an executing assembly is to call the Assembly.GetExecutingAssembly () method.
After getting an ResourceManager instance, you can get the corresponding resource by specifying the key name.
The following table shows some of the controls used in the program:
Category TextBox TextBox TextBox TextBox PictureBox
Name username sex birthday salary photo
These controls can be dragged and dropped directly from the toolbox into the designer.
Complete source code is:
Method 1:
 
using System.reflection; 
using System.Resources; 
private System.Resources.ResourceManager rm; 
public Form1() 
{ 
InitializeComponent(); 
Assembly assembly=Assembly.GetExecutingAssembly();// Gets the current main assembly  
Rm=new ResourceManager("ResourceUserinfo.Userinfo",assembly);// Instantiate the resource management class  
photo.iamge=(Image)rm.GetObjetct("Photo"); 
username.Text=rm.GetString("Username"); 
sex.Text=rm.GetString("Sex"); 
birthday.Text=rm.GetString("Birthday"); 
salary.Text=rm.GetString("Salary"); 
} 

Method 2:
 
Assembly assm = this.GetType().Assembly;//Assembly.LoadFrom( Assembly path ); 
foreach (string resName in assm.GetManifestResourceNames()) 
{ 
Stream stream = assm.GetManifestResourceStream(resName); 
ResourceReader rr = new ResourceReader(stream); 
IDictionaryEnumerator enumerator = rr.GetEnumerator(); 
while (enumerator.MoveNext()) 
{ 
DictionaryEntry de = (DictionaryEntry)enumerator.Current; 
//de.Key Is the resource name  
//de.Value It's the resource content  
} 
} 

Run the above code to extract the contents of the resource file.
Tasting read (21) comment (0) edit
The use of the DoDragDrop method
The DoDragDrop method is used to start a drag-and-drop operation on an object.
The definition in the class library is:
 
[UIPermissionAttribute(SecurityAction.Demand, Clipboard = UIPermissionClipboard.OwnClipboard)] 
public DragDropEffects DoDragDrop( 
Object data, 
DragDropEffects allowedEffects 
) 

Where the data parameter is the data to be dragged and dropped. If the dragging operation needs to interoperate with the application of another process, the data represented by data should be the basic managed class (String,BitMap, or MetaFile), or the object that implements ISerializable or IDataObject. The allowedEffects parameter represents the drag-and-drop effect and is an enumeration value (DragDropEffects). The return value is also an DragDropEffects enumeration value.
When you start dragging a data object by calling the DoDragDrop method, DoDragDrops checks whether the control under the current cursor position is effectively placing the target during the drag-and-drop process. If the control under the current cursor is a valid drop target, the GiveFeedBack event is raised with the specified drag-and-drop effect. The DoDragDrops method tracks changes in cursor position, keyboard state, and mouse state simultaneously while detecting whether the current cursor is a valid drag-and-drop target.
(1) if a window is removed, an DragLeave event is raised.
(2) if another control is moved in, the DragEnter event for that control is raised.
(3) if the mouse moves, but stays in a control, DragOver event will be raised.
If the keyboard or mouse state is detected to have changed, the QueryContinueDrag event of the drag-and-drop source is raised, and the Action property value of the QueryContinueDragEventArgs of the event is determined to continue the drag, place the data, or cancel the operation.
(1) if the Action attribute is specified as Continue, an DragOver event will be raised.
(2) if the Action attribute is specified as Drop, the placement effect is returned to the source so that the application can perform appropriate operations on the data; For example, if it is a move operation, cut the data.
(3) if the value of DragAction is Cancel, an DragLeave event is raised
Extract 1 piece of sample code from csdn:
The following code example demonstrates the drag-and-drop operation between two ListBox controls. The example calls the DoDragDrop method when the drag action is started. During the MouseDown event, if the mouse moves more distance from the mouse position than SystemInformation.. ::.DragSize, start the drag. The IndexFromPoint method is used to determine the index of the item to be dragged during the MouseDown event.
The example also demonstrates how to use a custom cursor for drag-and-drop operations. The example requires the presence of two cursor files in the application directory: 3dwarro.cur and 3dwno.cur for custom dragging of the cursor and forbidden parking of the cursor, respectively. If UseCustomCursorsCheckCheckBox is selected, a custom cursor is used. The custom cursor is set in the GiveFeedback event handler.
The keyboard state is calculated in the DragOver event handler on the right ListBox to determine which drag operation will occur based on the state of Shift, Ctrl, Alt, or Ctrl+Alt keys. The location of the placement action in ListBox is also determined during the DragOver event. If the data to be placed is not String, DragDropEffects will set DragEventArgs.sEffect to None. Finally, the parking status is displayed in DropLocationLabelLabel.
The data to be placed for right ListBox is determined in the DragDrop event handler and the String value is added in the appropriate location in ListBox. If the drag action moves outside the form's border, the QueryContinueDrag event handler cancels the drag and drop action
 
using System; 
using System.Drawing; 
using System.Windows.Forms; 
namespace Snip_DragNDrop 
{ 
public class Form1 : System.Windows.Forms.Form 
{ 
private System.Windows.Forms.ListBox ListDragSource; 
private System.Windows.Forms.ListBox ListDragTarget; 
private System.Windows.Forms.CheckBox UseCustomCursorsCheck; 
private System.Windows.Forms.Label DropLocationLabel; 
private int indexOfItemUnderMouseToDrag; 
private int indexOfItemUnderMouseToDrop; 
private Rectangle dragBoxFromMouseDown; 
private Point screenOffset; 
private Cursor MyNoDropCursor; 
private Cursor MyNormalCursor; 
/// The main entry point for the application. 
[STAThread] 
static void Main() 
{ 
Application.Run(new Form1()); 
} 
public Form1() 
{ 
this.ListDragSource = new System.Windows.Forms.ListBox(); 
this.ListDragTarget = new System.Windows.Forms.ListBox(); 
this.UseCustomCursorsCheck = new System.Windows.Forms.CheckBox(); 
this.DropLocationLabel = new System.Windows.Forms.Label(); 
this.SuspendLayout(); 
// ListDragSource 
this.ListDragSource.Items.AddRange(new object[] {"one", "two", "three", "four", 
"five", "six", "seven", "eight", 
"nine", "ten"}); 
this.ListDragSource.Location = new System.Drawing.Point(10, 17); 
this.ListDragSource.Size = new System.Drawing.Size(120, 225); 
this.ListDragSource.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ListDragSource_MouseDown); 
this.ListDragSource.QueryContinueDrag += new System.Windows.Forms.QueryContinueDragEventHandler(this.ListDragSource_QueryContinueDrag); 
this.ListDragSource.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ListDragSource_MouseUp); 
this.ListDragSource.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ListDragSource_MouseMove); 
this.ListDragSource.GiveFeedback += new System.Windows.Forms.GiveFeedbackEventHandler(this.ListDragSource_GiveFeedback); 
// ListDragTarget 
this.ListDragTarget.AllowDrop = true; 
this.ListDragTarget.Location = new System.Drawing.Point(154, 17); 
this.ListDragTarget.Size = new System.Drawing.Size(120, 225); 
this.ListDragTarget.DragOver += new System.Windows.Forms.DragEventHandler(this.ListDragTarget_DragOver); 
this.ListDragTarget.DragDrop += new System.Windows.Forms.DragEventHandler(this.ListDragTarget_DragDrop); 
this.ListDragTarget.DragEnter += new System.Windows.Forms.DragEventHandler(this.ListDragTarget_DragEnter); 
this.ListDragTarget.DragLeave += new System.EventHandler(this.ListDragTarget_DragLeave); 
// UseCustomCursorsCheck 
this.UseCustomCursorsCheck.Location = new System.Drawing.Point(10, 243); 
this.UseCustomCursorsCheck.Size = new System.Drawing.Size(137, 24); 
this.UseCustomCursorsCheck.Text = "Use Custom Cursors"; 
// DropLocationLabel 
this.DropLocationLabel.Location = new System.Drawing.Point(154, 245); 
this.DropLocationLabel.Size = new System.Drawing.Size(137, 24); 
this.DropLocationLabel.Text = "None"; 
// Form1 
this.ClientSize = new System.Drawing.Size(292, 270); 
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.ListDragSource, 
this.ListDragTarget, this.UseCustomCursorsCheck, 
this.DropLocationLabel}); 
this.Text = "drag-and-drop Example"; 
this.ResumeLayout(false); 
} 
private void ListDragSource_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) 
{ 
// Get the index of the item the mouse is below. 
indexOfItemUnderMouseToDrag = ListDragSource.IndexFromPoint(e.X, e.Y); 
if (indexOfItemUnderMouseToDrag != ListBox.NoMatches) { 
// Remember the point where the mouse down occurred. The DragSize indicates 
// the size that the mouse can move before a drag event should be started. 
Size dragSize = SystemInformation.DragSize; 
// Create a rectangle using the DragSize, with the mouse position being 
// at the center of the rectangle. 
dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width /2), 
e.Y - (dragSize.Height /2)), dragSize); 
} else 
// Reset the rectangle if the mouse is not over an item in the ListBox. 
dragBoxFromMouseDown = Rectangle.Empty; 
} 
private void ListDragSource_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { 
// Reset the drag rectangle when the mouse button is raised. 
dragBoxFromMouseDown = Rectangle.Empty; 
} 
private void ListDragSource_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) 
{ 
if ((e.Button & MouseButtons.Left) == MouseButtons.Left) { 
// If the mouse moves outside the rectangle, start the drag. 
if (dragBoxFromMouseDown != Rectangle.Empty && 
!dragBoxFromMouseDown.Contains(e.X, e.Y)) { 
// Create custom cursors for the drag-and-drop operation. 
try { 
MyNormalCursor = new Cursor("3dwarro.cur"); 
MyNoDropCursor = new Cursor("3dwno.cur"); 
} catch { 
// An error occurred while attempting to load the cursors, so use 
// standard cursors. 
UseCustomCursorsCheck.Checked = false; 
}finally { 
// The screenOffset is used to account for any desktop bands 
// that may be at the top or left side of the screen when 
// determining when to cancel the drag drop operation. 
screenOffset = SystemInformation.WorkingArea.Location; 
// Proceed with the drag-and-drop, passing in the list item. 
DragDropEffects dropEffect = ListDragSource.DoDragDrop(ListDragSource.Items[indexOfItemUnderMouseToDrag], DragDropEffects.All | DragDropEffects.Link); 
// If the drag operation was a move then remove the item. 
if (dropEffect == DragDropEffects.Move) { 
ListDragSource.Items.RemoveAt(indexOfItemUnderMouseToDrag); 
// Selects the previous item in the list as long as the list has an item. 
if (indexOfItemUnderMouseToDrag > 0) 
ListDragSource.SelectedIndex = indexOfItemUnderMouseToDrag -1; 
else if (ListDragSource.Items.Count > 0) 
// Selects the first item. 
ListDragSource.SelectedIndex =0; 
} 
// Dispose of the cursors since they are no longer needed. 
if (MyNormalCursor != null) 
MyNormalCursor.Dispose(); 
if (MyNoDropCursor != null) 
MyNoDropCursor.Dispose(); 
} 
} 
} 
} 
private void ListDragSource_GiveFeedback(object sender, System.Windows.Forms.GiveFeedbackEventArgs e) 
{ 
// Use custom cursors if the check box is checked. 
if (UseCustomCursorsCheck.Checked) { 
// Sets the custom cursor based upon the effect. 
e.UseDefaultCursors = false; 
if ((e.Effect & DragDropEffects.Move) == DragDropEffects.Move) 
Cursor.Current = MyNormalCursor; 
else 
Cursor.Current = MyNoDropCursor; 
} 
} 
private void ListDragTarget_DragOver(object sender, System.Windows.Forms.DragEventArgs e) 
{ 
// Determine whether string data exists in the drop data. If not, then 
// the drop effect reflects that the drop cannot occur. 
if (!e.Data.GetDataPresent(typeof(System.String))) { 
e.Effect = DragDropEffects.None; 
DropLocationLabel.Text = "None - no string data."; 
return; 
} 
// Set the effect based upon the KeyState. 
if ((e.KeyState & (8+32)) == (8+32) && 
(e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) { 
// KeyState 8 + 32 = CTL + ALT 
// Link drag-and-drop effect. 
e.Effect = DragDropEffects.Link; 
} else if ((e.KeyState & 32) == 32 && 
(e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) { 
// ALT KeyState for link. 
e.Effect = DragDropEffects.Link; 
} else if ((e.KeyState & 4) == 4 && 
(e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) { 
// SHIFT KeyState for move. 
e.Effect = DragDropEffects.Move; 
} else if ((e.KeyState & 8) == 8 && 
(e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) { 
// CTL KeyState for copy. 
e.Effect = DragDropEffects.Copy; 
} else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) { 
// By default, the drop action should be move, if allowed. 
e.Effect = DragDropEffects.Move; 
} else 
e.Effect = DragDropEffects.None; 
// Get the index of the item the mouse is below. 
// The mouse locations are relative to the screen, so they must be 
// converted to client coordinates. 
indexOfItemUnderMouseToDrop = 
ListDragTarget.IndexFromPoint(ListDragTarget.PointToClient(new Point(e.X, e.Y))); 
// Updates the label text. 
if (indexOfItemUnderMouseToDrop != ListBox.NoMatches){ 
DropLocationLabel.Text = "Drops before item #" + (indexOfItemUnderMouseToDrop + 1); 
} else 
DropLocationLabel.Text = "Drops at the end."; 
} 
private void ListDragTarget_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) 
{ 
// Ensure that the list item index is contained in the data. 
if (e.Data.GetDataPresent(typeof(System.String))) { 
Object item = (object)e.Data.GetData(typeof(System.String)); 
// Perform drag-and-drop, depending upon the effect. 
if (e.Effect == DragDropEffects.Copy || 
e.Effect == DragDropEffects.Move) { 
// Insert the item. 
if (indexOfItemUnderMouseToDrop != ListBox.NoMatches) 
ListDragTarget.Items.Insert(indexOfItemUnderMouseToDrop, item); 
else 
ListDragTarget.Items.Add(item); 
} 
} 
// Reset the label text. 
DropLocationLabel.Text = "None"; 
} 
private void ListDragSource_QueryContinueDrag(object sender, System.Windows.Forms.QueryContinueDragEventArgs e) { 
// Cancel the drag if the mouse moves off the form. 
ListBox lb = sender as ListBox; 
if (lb != null) { 
Form f = lb.FindForm(); 
// Cancel the drag if the mouse moves off the form. The screenOffset 
// takes into account any desktop bands that may be at the top or left 
// side of the screen. 
if (((Control.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) || 
((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) || 
((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) || 
((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom)) { 
e.Action = DragAction.Cancel; 
} 
} 
} 
private void ListDragTarget_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) { 
// Reset the label text. 
DropLocationLabel.Text = "None"; 
} 
private void ListDragTarget_DragLeave(object sender, System.EventArgs e) { 
// Reset the label text. 
DropLocationLabel.Text = "None"; 
} 
} 
} 

The relationship between drag-and-drop operations and Microsoft's services, the container model, will be studied later.
Tasting (92) (0
About the use of interfaces
Overview: the use of interfaces embodies a general idea.
Application scenario 1 is:
(1) multiple classes are required to implement certain actions, which are not implemented in the same way.
For example, to create a condition to the form, to implement the plastic parameters, bool type parameters and string type parameters to add conditions to the form. The implementation details are different in the concrete implementation of shaping and string forms, as well as bool type added forms.
 
public interface IExpressionForm 
{ 
ConditionItemEntity CIEntity { get; set; } 
ConditionBranchEntity CIEntity { get; set; } 
event Handle OnExpressionHandled; } 

For each form, you need to include the CIEntity, CIEntity properties and OnExpressionHandled conditional events, so CIEntity, CIEntity, and OnExpressionHandled are defined in the IExpressionForm interface.
Then implement the condition of shaping parameters to add the form
 
public partial class frmNumericCondition : Form, IExpressionForm 
{ 
public frmNumericCondition() 
{ 
InitializeComponent(); 
} 
public ConditionItemEntity CIEntity { get; set; } 
public ConditionBranchEntity CBEntity { get; set; } 
public event Handle OnExpressionHandled; 
} 

Then add the form with a character parameter condition
 
public void AddResource( 
string name,// Key name  
string value// value  
); 
0
In the same way, other parameter type conditions are added to the form.
What are the benefits of my goal? Let's take a look at one of the functions I've defined to generate the form
 
public static IExpressionForm CreateExpressionForm(ConditionType ct) 
{ 
IExpressionForm frm = null; 
if (ct == ConditionType.bit) 
frm = new frmBitCondition(); 
else if (ct == ConditionType.datetime) 
frm = new frmDateTimeCondition(); 
else if (ct == ConditionType.numeric) 
frm = new frmNumericCondition(); 
else if (ct == ConditionType.varchar) 
frm = new frmVarcharCondition(); 
return frm; 
} 

As you can see from the definition, the return value type is IExpressionForm, which is the interface I defined above. This function can therefore return a class that implements the IExpressionForm interface. Such as frmVarcharCondition and frmNumericCondition.
This is a simple implementation of the factory pattern, the program can be very good extensibility.
The above is just the application scenario 1 of the interface, which I found when I was writing the code. It's not good. But also to write, 1 is to summarize the work and study, in the summary of the time can think and find, but also hope to give people reading the article 1 some help.


Related articles: