Search Results

Search found 1234 results on 50 pages for 'enum'.

Page 27/50 | < Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >

  • Simple iOS glDrawElements - BAD_ACCESS

    - by user699215
    You can copy paste this into the default OpenGl template created in Xcode. Why am I not seeing anything :-) It is strange as the glDrawArrays(GL_TRIANGLES, 0, 3); is working fine, but with glDrawElements(GL_TRIANGLE_STRIP, sizeof(indices)/sizeof(GLubyte), GL_UNSIGNED_BYTE, indices); Is giving BAD_ACCESS? Copy paste this into Xcode default OpenGl template: ViewController #import "ViewController.h" #define BUFFER_OFFSET(i) ((char *)NULL + (i)) // Uniform index. enum { UNIFORM_MODELVIEWPROJECTION_MATRIX, UNIFORM_NORMAL_MATRIX, NUM_UNIFORMS }; GLint uniforms[NUM_UNIFORMS]; // Attribute index. enum { ATTRIB_VERTEX, ATTRIB_NORMAL, NUM_ATTRIBUTES }; @interface ViewController () { GLKMatrix4 _modelViewProjectionMatrix; GLKMatrix3 _normalMatrix; float _rotation; GLuint _vertexArray; GLuint _vertexBuffer; NSArray* arrayOfVertex; } @property (strong, nonatomic) EAGLContext *context; @property (strong, nonatomic) GLKBaseEffect *effect; - (void)setupGL; - (void)tearDownGL; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; GLKView *view = (GLKView *)self.view; view.context = self.context; view.drawableDepthFormat = GLKViewDrawableDepthFormat24; [self setupGL]; } - (void)dealloc { [self tearDownGL]; if ([EAGLContext currentContext] == self.context) { [EAGLContext setCurrentContext:nil]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; if ([self isViewLoaded] && ([[self view] window] == nil)) { self.view = nil; [self tearDownGL]; if ([EAGLContext currentContext] == self.context) { [EAGLContext setCurrentContext:nil]; } self.context = nil; } // Dispose of any resources that can be recreated. } GLuint vertexBufferID; GLuint indexBufferID; static const GLfloat vertices[9] = { -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5 }; static const GLubyte indices[3] = { 0, 1, 2 }; - (void)setupGL { [EAGLContext setCurrentContext:self.context]; // [self loadShaders]; self.effect = [[GLKBaseEffect alloc] init]; self.effect.light0.enabled = GL_TRUE; self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f); glEnable(GL_DEPTH_TEST); // glGenVertexArraysOES(1, &_vertexArray); // glBindVertexArrayOES(_vertexArray); glGenBuffers(1, &vertexBufferID); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glGenBuffers(1, &indexBufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glEnableVertexAttribArray(GLKVertexAttribPosition); glVertexAttribPointer(GLKVertexAttribPosition, // Specifies the index of the generic vertex attribute to be modified. 3, // Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4. GL_FLOAT, // GL_FALSE, // 0, // BUFFER_OFFSET(0)); // // glBindVertexArrayOES(0); } - (void)tearDownGL { [EAGLContext setCurrentContext:self.context]; glDeleteBuffers(1, &_vertexBuffer); glDeleteVertexArraysOES(1, &_vertexArray); self.effect = nil; } #pragma mark - GLKView and GLKViewController delegate methods - (void)update { float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height); GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f); self.effect.transform.projectionMatrix = projectionMatrix; GLKMatrix4 baseModelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -4.0f); baseModelViewMatrix = GLKMatrix4Rotate(baseModelViewMatrix, _rotation, 0.0f, 1.0f, 0.0f); // Compute the model view matrix for the object rendered with GLKit GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -1.5f); modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f); modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix); self.effect.transform.modelviewMatrix = modelViewMatrix; // Compute the model view matrix for the object rendered with ES2 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, 1.5f); modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f); modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix); _normalMatrix = GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3(modelViewMatrix), NULL); _modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix); _rotation += self.timeSinceLastUpdate * 0.5f; } int i; - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect { glClearColor(0.65f, 0.65f, 0.65f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // glBindVertexArrayOES(_vertexArray); // Render the object with GLKit [self.effect prepareToDraw]; //glDrawArrays(GL_TRIANGLES, 0, 3); // Render the object again with ES2 // glDrawArrays(GL_TRIANGLES, 0, 3); glDrawElements(GL_TRIANGLE_STRIP, sizeof(indices)/sizeof(GLubyte), GL_UNSIGNED_BYTE, indices); } @end

    Read the article

  • A*, Tile costs and heuristic; How to approach

    - by Kevin Toet
    I'm doing exercises in tile games and AI to improve my programming. I've written a highly unoptimised pathfinder that does the trick and a simple tile class. The first problem i ran into was that the heuristic was rounded to int's which resulted in very straight paths. Resorting a Euclidian Heuristic seemed to fixed it as opposed to use the Manhattan approach. The 2nd problem I ran into was when i tried added tile costs. I was hoping to use the value's of the flags that i set on the tiles but the value's were too small to make the pathfinder consider them a huge obstacle so i increased their value's but that breaks the flags a certain way and no paths were found anymore. So my questions, before posting the code, are: What am I doing wrong that the Manhatten heuristic isnt working? What ways can I store the tile costs? I was hoping to (ab)use the enum flags for this The path finder isnt considering the chance that no path is available, how do i check this? Any code optimisations are welcome as I'd love to improve my coding. public static List<Tile> FindPath( Tile startTile, Tile endTile, Tile[,] map ) { return FindPath( startTile, endTile, map, TileFlags.WALKABLE ); } public static List<Tile> FindPath( Tile startTile, Tile endTile, Tile[,] map, TileFlags acceptedFlags ) { List<Tile> open = new List<Tile>(); List<Tile> closed = new List<Tile>(); open.Add( startTile ); Tile tileToCheck; do { tileToCheck = open[0]; closed.Add( tileToCheck ); open.Remove( tileToCheck ); for( int i = 0; i < tileToCheck.neighbors.Count; i++ ) { Tile tile = tileToCheck.neighbors[ i ]; //has the node been processed if( !closed.Contains( tile ) && ( tile.flags & acceptedFlags ) != 0 ) { //Not in the open list? if( !open.Contains( tile ) ) { //Set G int G = 10; G += tileToCheck.G; //Set Parent tile.parentX = tileToCheck.x; tile.parentY = tileToCheck.y; tile.G = G; //tile.H = Math.Abs(endTile.x - tile.x ) + Math.Abs( endTile.y - tile.y ) * 10; //TODO omg wtf and other incredible stories tile.H = Vector2.Distance( new Vector2( tile.x, tile.y ), new Vector2(endTile.x, endTile.y) ); tile.Cost = tile.G + tile.H + (int)tile.flags; //Calculate H; Manhattan style open.Add( tile ); } //Update the cost if it is else { int G = 10;//cost of going to non-diagonal tiles G += map[ tile.parentX, tile.parentY ].G; //If this path is shorter (G cost is lower) then change //the parent cell, G cost and F cost. if ( G < tile.G ) //if G cost is less, { tile.parentX = tileToCheck.x; //change the square's parent tile.parentY = tileToCheck.y; tile.G = G;//change the G cost tile.Cost = tile.G + tile.H + (int)tile.flags; // add terrain cost } } } } //Sort costs open = open.OrderBy( o => o.Cost).ToList(); } while( tileToCheck != endTile ); closed.Reverse(); List<Tile> validRoute = new List<Tile>(); Tile currentTile = closed[ 0 ]; validRoute.Add( currentTile ); do { //Look up the parent of the current cell. currentTile = map[ currentTile.parentX, currentTile.parentY ]; currentTile.renderer.material.color = Color.green; //Add tile to list validRoute.Add( currentTile ); } while ( currentTile != startTile ); validRoute.Reverse(); return validRoute; } And my Tile class: [Flags] public enum TileFlags: int { NONE = 0, DIRT = 1, STONE = 2, WATER = 4, BUILDING = 8, //handy WALKABLE = DIRT | STONE | NONE, endofenum } public class Tile : MonoBehaviour { //Tile Properties public int x, y; public TileFlags flags = TileFlags.DIRT; public Transform cachedTransform; //A* properties public int parentX, parentY; public int G; public float Cost; public float H; public List<Tile> neighbors = new List<Tile>(); void Awake() { cachedTransform = transform; } }

    Read the article

  • Objected oriented approach to structure inside structure

    - by RishiD
    This is for C++ but should apply to any OO language. Trying to figure out the correct object oriented apporach to do the following (this is what I do in C). struct Container { enum type; union { TypeA a; TypeB b; }; } The type field determines if it TypeA or TypeB object. I am using this to handle responses coming back from a connection, they get parsed and get put into this structure and then based on the message type the appropriate fields get filled in. e.g. struct Container parseResponse(bufferIn, bufferLength); Is there an OO approach for doing this?

    Read the article

  • OpenGL problem with FBO integer texture and color attachment

    - by Grieverheart
    In my simple renderer, I have 2 FBOs one that contains diffuse, normals, instance ID and depth in that order and one that I use store the ssao result. The textures I use for the first FBO are RGB8, RGBA16F, R32I and GL_DEPTH_COMPONENT32F for the depth. For the second FBO I use an R16F texture. My rendering process is to first render to everything I mentioned in the first FBO, then bind depth and normals textures for reading for the ssao pass and write to the second FBO. After that I bind the second FBO's texture for reading in my blur shader and bind the first FBO for writing. What I intend to do is to write the blurred ssao value to the alpha component of the Normals texture. Here are where the problems start. First of all, I use shading language 3.3, which my graphics card does support. I manage ouputs in my shaders using layout(location = #). Now, the normals texture should be bound to color attachment 1, but when I use 1, it seems to write to my diffuse texture which should be in color attachment 0. When I instead use layout(location = 0), it gets correctly written to my normals texture. Besides this, my instance ID texture also gets resets after running the blur shader which is weird because if I use a float texture and write to it instanceID / nInstances, the texture doesn't get reset after the blur shader has ran. Here is how I prepare my first FBO: bool CGBuffer::Init(unsigned int WindowWidth, unsigned int WindowHeight){ //Create FBO glGenFramebuffers(1, &m_fbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo); //Create gbuffer and Depth Buffer Textures glGenTextures(GBUFF_NUM_TEXTURES, &m_textures[0]); glGenTextures(1, &m_depthTexture); //prepare gbuffer for(unsigned int i = 0; i < GBUFF_NUM_TEXTURES; i++){ glBindTexture(GL_TEXTURE_2D, m_textures[i]); if(i == GBUFF_TEXTURE_TYPE_NORMAL) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WindowWidth, WindowHeight, 0, GL_RGBA, GL_FLOAT, NULL); else if(i == GBUFF_TEXTURE_TYPE_DIFFUSE) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, WindowWidth, WindowHeight, 0, GL_RGB, GL_FLOAT, NULL); else if(i == GBUFF_TEXTURE_TYPE_ID) glTexImage2D(GL_TEXTURE_2D, 0, GL_R32I, WindowWidth, WindowHeight, 0, GL_RED_INTEGER, GL_INT, NULL); else{ std::cout << "Error in FBO initialization" << std::endl; return false; } glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, m_textures[i], 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } //prepare depth buffer glBindTexture(GL_TEXTURE_2D, m_depthTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); GLenum DrawBuffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2}; glDrawBuffers(GBUFF_NUM_TEXTURES, DrawBuffers); GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(Status != GL_FRAMEBUFFER_COMPLETE){ std::cout << "FB error, status 0x" << std::hex << Status << std::endl; return false; } //Restore default framebuffer glBindFramebuffer(GL_FRAMEBUFFER, 0); return true; } where I use an enum defined as, enum GBUFF_TEXTURE_TYPE{ GBUFF_TEXTURE_TYPE_DIFFUSE, GBUFF_TEXTURE_TYPE_NORMAL, GBUFF_TEXTURE_TYPE_ID, GBUFF_NUM_TEXTURES }; Am I missing some kind of restriction? Does the color attachment of the FBO's textures somehow gets reset i.e. I'm using a re-size function which re-sizes the textures of the FBO but should I perhaps call glFramebufferTexture2D again too? EDIT: Here is the shader in question: #version 330 core uniform sampler2D aoSampler; uniform vec2 TEXEL_SIZE; // x = 1/res x, y = 1/res y uniform bool use_blur; noperspective in vec2 TexCoord; layout(location = 0) out vec4 out_AO; void main(void){ if(use_blur){ float result = 0.0; for(int i = -1; i < 2; i++){ for(int j = -1; j < 2; j++){ vec2 offset = vec2(TEXEL_SIZE.x * i, TEXEL_SIZE.y * j); result += texture(aoSampler, TexCoord + offset).r; // -0.004 because the texture seems to be a bit displaced } } out_AO = vec4(vec3(0.0), result / 9); } else out_AO = vec4(vec3(0.0), texture(aoSampler, TexCoord).r); }

    Read the article

  • Best practice Java - String array constant and indexing it

    - by Pramod
    For string constants its usual to use a class with final String values. But whats the best practice for storing string array. I want to store different categories in a constant array and everytime a category has been selected, I want to know which category it belongs to and process based on that. Addition : To make it more clear, I have a categories A,B,C,D,E which is a constant array. Whenever a user clicks one of the items(button will have those texts) I should know which item was clicked and do processing on that. I can define an enum(say cat) and everytime do if clickedItem == cat.A .... else if clickedItem = cat.B .... else if .... or even register listeners for each item seperately. But I wanted to know the best practice for doing handling these kind of problems.

    Read the article

  • Designing exceptions for conversion failures

    - by Mr.C64
    Suppose there are some methods to convert from "X" to "Y" and vice versa; the conversion may fail in some cases, and exceptions are used to signal conversion errors in those cases. Which would be the best option for defining exception classes in this context? A single XYConversionException class, with an attribute (e.g. an enum) specifying the direction of the conversion (e.g. ConversionFromXToY, ConversionFromYToX). A XYConversionException class, with two derived classes ConversionFromXToYException and ConversionFromYToXException. ConversionFromXToYException and ConversionFromYToXException classes without a common base class.

    Read the article

  • Space invaders clone not moving properly

    - by ThePlan
    I'm trying to make a basic space invaders clone in allegro 5, I've got my game set up, basic events and such, here is the code: #include <allegro5/allegro.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_primitives.h> #include <allegro5/allegro_font.h> #include <allegro5/allegro_ttf.h> #include "Entity.h" // GLOBALS ========================================== const int width = 500; const int height = 500; const int imgsize = 3; bool key[5] = {false, false, false, false, false}; bool running = true; bool draw = true; // FUNCTIONS ======================================== void initSpaceship(Spaceship &ship); void moveSpaceshipRight(Spaceship &ship); void moveSpaceshipLeft(Spaceship &ship); void initInvader(Invader &invader); void moveInvaderRight(Invader &invader); void moveInvaderLeft(Invader &invader); void initBullet(Bullet &bullet); void fireBullet(); void doCollision(); void updateInvaders(); void drawText(); enum key_t { UP, DOWN, LEFT, RIGHT, SPACE }; enum source_t { INVADER, DEFENDER }; int main(void) { if(!al_init()) { return -1; } Spaceship ship; Invader invader; Bullet bullet; al_init_image_addon(); al_install_keyboard(); al_init_font_addon(); al_init_ttf_addon(); ALLEGRO_DISPLAY *display = al_create_display(width, height); ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); ALLEGRO_TIMER *timer = al_create_timer(1.0 / 60); ALLEGRO_BITMAP *images[imgsize]; ALLEGRO_FONT *font1 = al_load_font("arial.ttf", 20, 0); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); images[0] = al_load_bitmap("defender.bmp"); images[1] = al_load_bitmap("invader.bmp"); images[2] = al_load_bitmap("explosion.bmp"); al_convert_mask_to_alpha(images[0], al_map_rgb(0, 0, 0)); al_convert_mask_to_alpha(images[1], al_map_rgb(0, 0, 0)); al_convert_mask_to_alpha(images[2], al_map_rgb(0, 0, 0)); initSpaceship(ship); initBullet(bullet); initInvader(invader); al_start_timer(timer); while(running) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_TIMER) { draw = true; if(key[RIGHT] == true) moveSpaceshipRight(ship); if(key[LEFT] == true) moveSpaceshipLeft(ship); } else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) running = false; else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: running = false; break; case ALLEGRO_KEY_LEFT: key[LEFT] = true; break; case ALLEGRO_KEY_RIGHT: key[RIGHT] = true; break; case ALLEGRO_KEY_SPACE: key[SPACE] = true; break; } } else if(ev.type == ALLEGRO_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_LEFT: key[LEFT] = false; break; case ALLEGRO_KEY_RIGHT: key[RIGHT] = false; break; case ALLEGRO_KEY_SPACE: key[SPACE] = false; break; } } if(draw && al_is_event_queue_empty(event_queue)) { draw = false; al_draw_bitmap(images[0], ship.pos_x, ship.pos_y, 0); al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); } } al_destroy_font(font1); al_destroy_event_queue(event_queue); al_destroy_timer(timer); for(int i = 0; i < imgsize; i++) al_destroy_bitmap(images[i]); al_destroy_display(display); } // FUNCTION LOGIC ====================================== void initSpaceship(Spaceship &ship) { ship.lives = 3; ship.speed = 2; ship.pos_x = width / 2; ship.pos_y = height - 20; } void initInvader(Invader &invader) { invader.health = 100; invader.count = 40; invader.speed = 0.5; invader.pos_x = 300; invader.pos_y = 300; } void initBullet(Bullet &bullet) { bullet.speed = 10; } void moveSpaceshipRight(Spaceship &ship) { ship.pos_x += ship.speed; if(ship.pos_x >= width) ship.pos_x = width-30; } void moveSpaceshipLeft(Spaceship &ship) { ship.pos_x -= ship.speed; if(ship.pos_x <= 0) ship.pos_x = 0+30; } However it's not behaving the way I want it to behave, in fact the behavior for the ship movement is un-normal. Basically I specified that the ship only moves when the right/left key is down, however the ship is moving constantly to the direction of the key pressed, it never stops although it should only move while my key is down. Even more weird behavior, when I press the opposite key the ship completely stops no matter what else I press. What's wrong with the code? Why does the ship move constantly even after I specified it only moves when a key is down?

    Read the article

  • I want to try and find an RFC for Business Listings.

    - by nc01
    I'm trying to figure out how to find out if there's a good standard format for sharing business information such as: Business Name Address - well-defined fields Lat,Lng Coords Business Type - maybe from a well-defined enum, my starting point contains Retail,Food,Drink,Coffee,Service Hours of operation - including a spot for 'except laksdasd' or 'sometimes we open late' which could be just plain language Business Keywords - don't know if this is asking too much. how well do http meta tags work in practice? So, if no such thing exists, is this something I can submit to IETF? I can't currently find it on http://www.rfc-editor.org/cgi-bin/rfcsearch.pl , and vCard doesn't suit my needs.. Thanks!

    Read the article

  • XNA When to call LoadContent

    - by Peteyslatts
    I have an enum in my game that denotes the game state ie MainMenu, InGame, GameOver, Exit and I was wondering if it would be advisable to add a new one in for PrepGame - in which the game creates viewports for however many players there are, creates the battlefield etc. I feel like this is a good idea except for one thing: should I make a call back to LoadContent() in this state? I could just put a switch statement in the LoadContent for my currentGameState. If it equals PrepGame load things like the skybox, ship models, texures, HUD graphics etc. Or is it a good idea to create an Asset Manager class in the first call to LoadContent() and load everything then. I feel like both approaches have different benefits: faster, but more load times vs slower initial load time, but then all my objects are referencing the same variables so I only have to load each on once. Any help is greatly appreciated. Thanks, Peter

    Read the article

  • I want to try and find and RFC for Business Listings.

    - by nc01
    I'm trying to figure out how to find out if there's a good standard format for sharing business information such as: Business Name Address - well-defined fields Lat,Lng Coords Business Type - maybe from a well-defined enum, my starting point contains Retail,Food,Drink,Coffee,Service Hours of operation - including a spot for 'except laksdasd' or 'sometimes we open late' which could be just plain language Business Keywords - don't know if this is asking too much. how well do http meta tags work in practice? So, if no such thing exists, is this something I can submit to IETF? I can't currently find it on http://www.rfc-editor.org/cgi-bin/rfcsearch.pl , and vCard doesn't suit my needs.. Thanks!

    Read the article

  • Error when updating enumerated value?

    - by igrad
    Once upon a time, there was a Player class (simplified version) enum animState{RUNNING,JUMPING,FALLING,IDLING}; class Player { public: Player(int x, int y); void handle(); void show(); ~Player(); private: int m_x; int m_y; animState playerAnimState; } There was also a "handle" function-member, which took care of all movement and collisions for the player: #include "player.h" void Player::handle() { if(/*Player presses 'D' key*/) { m_x++; playerAnimState = RUNNING; } //Other stuff that is just there to look nice Through lots of experimentation with "//" and "/**/", I've found that I consistently get an error at "playerAnimState = RUNNING." Have I broken some enumeration rule? Does my laptop really suck that bad? I hate to post a "fix my code for me" question, but I'm not very seasoned with enums.

    Read the article

  • Playing with aspx page cycle using JustMock

    In this post , I will cover a test code that will mock the various elements needed to complete a HTTP page request and  assert the expected page cycle steps. To begin, i have a simple enumeration that has my predefined page steps: public enum PageStep {     PreInit,     Load,     PreRender,     UnLoad } Once doing so, i  first...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • How to print PCL Directly to the printer? Vb.net VS 2010

    - by Justin
    Good day, I've been trying to upgrade an old Print Program that prints raw pcl directly to the printer. The print program takes a PCL Mask and a PCL Batch Spool File (just pcl with page turn commands, I think) merges them and sends them off to the printer. I'm able to send to the Printer a file stream of PCL but I get mixed results and i do not understand why printing is so difficult under .net. I mean yes there is the PrintDocument class, but to print PCL... Let's just say I'm ready to detach my printer from the network and burn it a live. Here is my class PrintDirect (rather a hybrid class) Imports System Imports System.Text Imports System.Runtime.InteropServices <StructLayout(LayoutKind.Sequential)> _ Public Structure DOCINFO <MarshalAs(UnmanagedType.LPWStr)> _ Public pDocName As String <MarshalAs(UnmanagedType.LPWStr)> _ Public pOutputFile As String <MarshalAs(UnmanagedType.LPWStr)> _ Public pDataType As String End Structure 'DOCINFO Public Class PrintDirect <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=False, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function OpenPrinter(ByVal pPrinterName As String, ByRef phPrinter As IntPtr, ByVal pDefault As Integer) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=False, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function StartDocPrinter(ByVal hPrinter As IntPtr, ByVal Level As Integer, ByRef pDocInfo As DOCINFO) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function StartPagePrinter(ByVal hPrinter As IntPtr) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Ansi, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function WritePrinter(ByVal hPrinter As IntPtr, ByVal data As String, ByVal buf As Integer, ByRef pcWritten As Integer) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function EndPagePrinter(ByVal hPrinter As IntPtr) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function EndDocPrinter(ByVal hPrinter As IntPtr) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Long End Function 'Helps uses to work with the printer Public Class PrintJob ''' <summary> ''' The address of the printer to print to. ''' </summary> ''' <remarks></remarks> Public PrinterName As String = "" Dim lhPrinter As New System.IntPtr() ''' <summary> ''' The object deriving from the Win32 API, Winspool.drv. ''' Use this object to overide the settings defined in the PrintJob Class. ''' </summary> ''' <remarks>Only use this when absolutly nessacary.</remarks> Public OverideDocInfo As New DOCINFO() ''' <summary> ''' The PCL Control Character or the ascii escape character. \x1b ''' </summary> ''' <remarks>ChrW(27)</remarks> Public Const PCL_Control_Character As Char = ChrW(27) ''' <summary> ''' Opens a connection to a printer, if false the connection could not be established. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function OpenPrint() As Boolean Dim rtn_val As Boolean = False PrintDirect.OpenPrinter(PrinterName, lhPrinter, 0) If Not lhPrinter = 0 Then rtn_val = True End If Return rtn_val End Function ''' <summary> ''' The name of the Print Document. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property DocumentName As String Get Return OverideDocInfo.pDocName End Get Set(ByVal value As String) OverideDocInfo.pDocName = value End Set End Property ''' <summary> ''' The type of Data that will be sent to the printer. ''' </summary> ''' <value>Send the print data type, usually "RAW" or "LPR". To overide use the OverideDocInfo Object</value> ''' <returns>The DataType as it was provided, if it is not part of the enumeration it is set to "UNKNOWN".</returns> ''' <remarks></remarks> Public Property DocumentDataType As PrintDataType Get Select Case OverideDocInfo.pDataType.ToUpper Case "RAW" Return PrintDataType.RAW Case "LPR" Return PrintDataType.LPR Case Else Return PrintDataType.UNKOWN End Select End Get Set(ByVal value As PrintDataType) OverideDocInfo.pDataType = [Enum].GetName(GetType(PrintDataType), value) End Set End Property Public Property DocumentOutputFile As String Get Return OverideDocInfo.pOutputFile End Get Set(ByVal value As String) OverideDocInfo.pOutputFile = value End Set End Property Enum PrintDataType UNKOWN = 0 RAW = 1 LPR = 2 End Enum ''' <summary> ''' Initializes the printing matrix ''' </summary> ''' <param name="PrintLevel">I have no idea what the hack this is...</param> ''' <remarks></remarks> Public Sub OpenDocument(Optional ByVal PrintLevel As Integer = 1) PrintDirect.StartDocPrinter(lhPrinter, PrintLevel, OverideDocInfo) End Sub ''' <summary> ''' Starts the next page. ''' </summary> ''' <remarks></remarks> Public Sub StartPage() PrintDirect.StartPagePrinter(lhPrinter) End Sub ''' <summary> ''' Writes a string to the printer, can be used to write out a section of the document at a time. ''' </summary> ''' <param name="data">The String to Send out to the Printer.</param> ''' <returns>The pcWritten as an integer, 0 may mean the writter did not write out anything.</returns> ''' <remarks>Warning the buffer is automatically created by the lenegth of the string.</remarks> Public Function WriteToPrinter(ByVal data As String) As Integer Dim pcWritten As Integer = 0 PrintDirect.WritePrinter(lhPrinter, data, data.Length - 1, pcWritten) Return pcWritten End Function Public Sub EndPage() PrintDirect.EndPagePrinter(lhPrinter) End Sub Public Sub CloseDocument() PrintDirect.EndDocPrinter(lhPrinter) End Sub Public Sub ClosePrint() PrintDirect.ClosePrinter(lhPrinter) End Sub ''' <summary> ''' Opens a connection to a printer and starts a new document. ''' </summary> ''' <returns>If false the connection could not be established. </returns> ''' <remarks></remarks> Public Function Open() As Boolean Dim rtn_val As Boolean = False rtn_val = OpenPrint() If rtn_val Then OpenDocument() End If Return rtn_val End Function ''' <summary> ''' Closes the document and closes the connection to the printer. ''' </summary> ''' <remarks></remarks> Public Sub Close() CloseDocument() ClosePrint() End Sub End Class End Class 'PrintDirect Here is how I print my file. I'm simple printing the PCL Masks, to show proof of concept. But I can't even do that. I can effectively create PCL and send it the printer without reading the file and it works fine... Plus I get mixed results with different stream reader text encoding as well. Dim pJob As New PrintDirect.PrintJob pJob.DocumentName = " test doc" pJob.DocumentDataType = PrintDirect.PrintJob.PrintDataType.RAW pJob.PrinterName = sPrinter.GetDevicePath '//This is where you'd stick your device name, sPrinter stands for Selected Printer from a dropdown (combobox). 'pJob.DocumentOutputFile = "C:\temp\test-spool.txt" If Not pJob.OpenPrint() Then MsgBox("Unable to connect to " & pJob.PrinterName, MsgBoxStyle.OkOnly, "Print Error") Exit Sub End If pJob.OpenDocument() pJob.StartPage() Dim sr As New IO.StreamReader(Me.txtFile.Text, Text.Encoding.ASCII) '//I've got best results with ASCII before, but only mized. Dim line As String = sr.ReadLine 'Fix for fly code on first run 'If line = 27 Then line = PrintDirect.PrintJob.PCL_Control_Character Do While (Not line Is Nothing) pJob.WriteToPrinter(line) line = sr.ReadLine Loop 'pJob.WriteToPrinter(ControlChars.FormFeed) pJob.EndPage() pJob.CloseDocument() sr.Close() sr.Dispose() sr = Nothing pJob.Close() I was able to get to print the mask, in the morning... now I'm getting strange printer characters scattered through 5 pages... I'm totally clueless. I must have changed something or the printer is at fault. You can access my test Check Mask, here http://kscserver.com/so/chk_mask.zip .

    Read the article

  • Using unmanaged code from managed code

    - by Harsha
    Hi I have my project developed in MFC which is unmnaged code. Now i need to create a similar application in C#, by reusing most of the MFC classes. Is it possible to directly export class/struct/enum from MFC dll, so that i can import it in my C# using dllimport and use it.?

    Read the article

  • Any significant performance improvement by using bitwise operators instead of plain int sums in C#?

    - by tunnuz
    Hello, I started working with C# a few weeks ago and I'm now in a situation where I need to build up a "bit set" flag to handle different cases in an algorithm. I have thus two options: enum RelativePositioning { LEFT = 0, RIGHT = 1, BOTTOM = 2, TOP = 3, FRONT = 4, BACK = 5 } pos = ((eye.X < minCorner.X ? 1 : 0) << RelativePositioning.LEFT) + ((eye.X > maxCorner.X ? 1 : 0) << RelativePositioning.RIGHT) + ((eye.Y < minCorner.Y ? 1 : 0) << RelativePositioning.BOTTOM) + ((eye.Y > maxCorner.Y ? 1 : 0) << RelativePositioning.TOP) + ((eye.Z < minCorner.Z ? 1 : 0) << RelativePositioning.FRONT) + ((eye.Z > maxCorner.Z ? 1 : 0) << RelativePositioning.BACK); Or: enum RelativePositioning { LEFT = 1, RIGHT = 2, BOTTOM = 4, TOP = 8, FRONT = 16, BACK = 32 } if (eye.X < minCorner.X) { pos += RelativePositioning.LEFT; } if (eye.X > maxCorner.X) { pos += RelativePositioning.RIGHT; } if (eye.Y < minCorner.Y) { pos += RelativePositioning.BOTTOM; } if (eye.Y > maxCorner.Y) { pos += RelativePositioning.TOP; } if (eye.Z > maxCorner.Z) { pos += RelativePositioning.FRONT; } if (eye.Z < minCorner.Z) { pos += RelativePositioning.BACK; } I could have used something as ((eye.X > maxCorner.X) << 1) but C# does not allow implicit casting from bool to int and the ternary operator was similar enough. My question now is: is there any performance improvement in using the first version over the second? Thank you Tommaso

    Read the article

  • NAPTR support for SLES

    - by egiakoum1984
    Do you know if there is a library in SLES9 or SLES10 which support NAPTR queries for ENUM functionality? The libadns doesn't support NAPTR. There are other libraries which support NAPTR queries but they aren't included in SLES.

    Read the article

  • Groovy syntax <? , <?>>

    - by bsreekanth
    Hello, I was going through one of the answer in SO, where I see the following syntax private Class<? extends Enum<?>> clazz what all the <? , <?>> expression means. Looks like generalize the implementation based on regex kind of expression. What is it called in Groovy... many thanks..

    Read the article

  • Custom Shortcut in Windows.Forms.Shortcut?

    - by Chris
    How would you go about assigning a custom shortcut in C# to a Menu item? Right now, it looks like it only uses what is available in the Windows.Forms.Shortcut enum. The combination that I want, Ctrl + DownArrow, is not available. Thanks. Chris

    Read the article

  • Java language features which have no equivalent in C#

    - by jthg
    Having mostly worked with C#, I tend to think in terms of C# features which aren't available in Java. After working extensively with Java over the last year, I've started to discover Java features that I wish were in C#. Below is a list of the ones that I'm aware of. Can anyone think of other Java language features which a person with a C# background may not realize exists? The articles http://www.25hoursaday.com/CsharpVsJava.html and http://en.wikipedia.org/wiki/Comparison_of_Java_and_C_Sharp give a very extensive list of differences between Java and C#, but I wonder whether I missed anything in the (very) long articles. I can also think of one feature (covariant return type) which I didn't see mentioned in either article. Please limit answers to language or core library features which can't be effectively implemented by your own custom code or third party libraries. Covariant return type - a method can be overridden by a method which returns a more specific type. Useful when implementing an interface or extending a class and you want a method to override a base method, but return a type more specific to your class. Enums are classes - an enum is a full class in java, rather than a wrapper around a primitive like in .Net. Java allows you to define fields and methods on an enum. Anonymous inner classes - define an anonymous class which implements a method. Although most of the use cases for this in Java are covered by delegates in .Net, there are some cases in which you really need to pass multiple callbacks as a group. It would be nice to have the choice of using an anonymous inner class. Checked exceptions - I can see how this is useful in the context of common designs used with Java applications, but my experience with .Net has put me in a habit of using exceptions only for unrecoverable conditions. I.E. exceptions indicate a bug in the application and are only caught for the purpose of logging. I haven't quite come around to the idea of using exceptions for normal program flow. strictfp - Ensures strict floating point arithmetic. I'm not sure what kind of applications would find this useful. fields in interfaces - It's possible to declare fields in interfaces. I've never used this. static imports - Allows one to use the static methods of a class without qualifying it with the class name. I just realized today that this feature exists. It sounds like a nice convenience.

    Read the article

  • Why does System.Windows.MessageBoxImage have enumeration sub-items with the same value?

    - by devdigital
    Hi, I'm trying to write my own abstraction over the MessageBoxImage enumeration, and see that MessageBoxImage is defined as: namespace System.Windows { public enum MessageBoxImage { None = 0, Error = 16, Hand = 16, Stop = 16, Question = 32, Exclamation = 48, Warning = 48, Asterisk = 64, Information = 64, } } How does the Show method determine whether to display an Error image or a Hand image? How would I write a method which takes a MessageBoxImage type, and return a CustomMessageBoxImage type which maps to the MessageBoxImage type, as I can't include both MessageBoxImage.Error and MessageBoxImage.Hand in the same switch statement?

    Read the article

  • Still getting duplicate token error after calling DuplicateTokenEx for impersonated token

    - by atconway
    I'm trying to return a Sytem.IntPtr from a service call so that the client can use impersonation to call some code. My imersonation code works properly if not passing the token back from a WCF service. I'm not sure why this is not working. I get the following error: "Invalid token for impersonation - it cannot be duplicated." Here is my code that does work except when I try to pass the token back from a service to a WinForm C# client to then impersonate. [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")] public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle); private IntPtr tokenHandle = new IntPtr(0); private IntPtr dupeTokenHandle = new IntPtr(0); [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public int Length; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; } public enum SecurityImpersonationLevel { SecurityAnonymous = 0, SecurityIdentification = 1, SecurityImpersonation = 2, SecurityDelegation = 3 } public enum TokenType { TokenPrimary = 1, TokenImpersonation = 2 } private const int MAXIMUM_ALLOWED = 0x2000000; [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public System.IntPtr GetWindowsUserToken(string UserName, string Password, string DomainName) { IntPtr tokenHandle = new IntPtr(0); IntPtr dupTokenHandle = new IntPtr(0); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; //Initialize the token handle tokenHandle = IntPtr.Zero; //Call LogonUser to obtain a handle to an access token for credentials supplied. bool returnValue = LogonUser(UserName, DomainName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); //Make sure a token was returned; if no populate the ResultCode and throw an exception: int ResultCode = 0; if (false == returnValue) { ResultCode = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ResultCode, "API call to LogonUser failed with error code : " + ResultCode); } SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.bInheritHandle = true; sa.Length = Marshal.SizeOf(sa); sa.lpSecurityDescriptor = (IntPtr)0; bool dupReturnValue = DuplicateTokenEx(tokenHandle, MAXIMUM_ALLOWED, ref sa, (int)SecurityImpersonationLevel.SecurityDelegation, (int)TokenType.TokenImpersonation, ref dupTokenHandle); int ResultCodeDup = 0; if (false == dupReturnValue) { ResultCodeDup = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ResultCode, "API call to DuplicateToken failed with error code : " + ResultCode); } //Return the user token return dupTokenHandle; } Any idea if I'm not using the call to DuplicateTokenEx correctly? According to the MSDN documentation I read here I should be able to create a token valid for delegation and use across the context on remote systems. When 'SecurityDelegation' is used, the server process can impersonate the client's security context on remote systems. Thanks!

    Read the article

  • how to change a button into a imagebutton in asp.net c#

    - by sweetsecret
    How to change the button into image button... the button in the beginning has "Pick a date" when clicked a calender pops out and the when a date is selected a label at the bottom reading the date comes in and the text on the button changes to disabled... i want to palce a imagebutton having a image icon of the calender and rest of the function will be the same.... the code as follows: using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; [assembly: TagPrefix("DatePicker", "EWS")] namespace EclipseWebSolutions.DatePicker { [DefaultProperty("Text")] [ToolboxData("<{0}:DatePicker runat=server")] [DefaultEvent("SelectionChanged")] [ValidationProperty("TextValue")] public class DatePicker : WebControl, INamingContainer { #region Properties public TextBox txtDate = new TextBox(); public Calendar calDate = new Calendar(); public Button btnDate = new Button(); public Panel pnlCalendar = new Panel(); private enum ViewStateConstants { ValidationGroup, RegularExpression, ErrorMessage, RegExText, CalendarPosition, FormatString, ExpandLabel, CollapseLabel, ApplyDefaultStyle, CausesValidation, } /// <summary> /// Defines the available display modes of this calendar. /// </summary> public enum CalendarDisplay { DisplayRight, DisplayBelow } /// <summary> /// Where to display the popup calendar. /// </summary> [Category("Behaviour")] [Localizable(true)] public CalendarDisplay CalendarPosition { get { if (ViewState[ViewStateConstants.CalendarPosition.ToString()] == null) { ViewState[ViewStateConstants.CalendarPosition.ToString()] = CalendarDisplay.DisplayRight; } return (CalendarDisplay)ViewState[ViewStateConstants.CalendarPosition.ToString()]; } set { ViewState[ViewStateConstants.CalendarPosition.ToString()] = value; } } /// <summary> /// Text version of the control's value, for use by ASP.NET validators. /// </summary> public string TextValue { get { return txtDate.Text; } } /// <summary> /// Holds the current date value of this control. /// </summary> [Category("Behaviour")] [Localizable(true)] [Bindable(true, BindingDirection.TwoWay)] public DateTime DateValue { get { try { if (txtDate.Text == "") return DateTime.MinValue; DateTime val = DateTime.Parse(txtDate.Text); return val; } catch (ArgumentNullException) { return DateTime.MinValue; } catch (FormatException) { return DateTime.MinValue; } } set { if (value == DateTime.MinValue) { txtDate.Text = ""; } else { txtDate.Text = value.ToShortDateString(); } } } [Category("Behavior"), Themeable(false), DefaultValue("")] public virtual string ValidationGroup { get { if (ViewState[ViewStateConstants.ValidationGroup.ToString()] == null) { return string.Empty; } else { return (string)ViewState[ViewStateConstants.ValidationGroup.ToString()]; } } set { ViewState[ViewStateConstants.ValidationGroup.ToString()] = value; } } /// <summary> /// The label of the exand button. Shown when the calendar is hidden. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("PickDate")] [Localizable(true)] public string ExpandButtonLabel { get { String s = (String)ViewState[ViewStateConstants.ExpandLabel.ToString()]; return ((s == null) ? "PickDate" : s); } set { ViewState[ViewStateConstants.ExpandLabel.ToString()] = value; } } /// <summary> /// The label of the collapse button. Shown when the calendar is visible. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("Disabled")] [Localizable(true)] public string CollapseButtonLabel { get { String s = (String)ViewState[ViewStateConstants.CollapseLabel.ToString()]; return ((s == null) ? "Disabled" : s); } set { ViewState[ViewStateConstants.CollapseLabel.ToString()] = value; } } /// <summary> /// Whether to apply the default style. Disable this if you want to apply a custom style, or to use themes and skins /// to style the control. /// </summary> [Category("Appearance")] [DefaultValue(true)] [Localizable(true)] public bool ApplyDefaultStyle { get { if (ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] == null) { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = true; } return (bool)ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()]; } set { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = value; } } /// <summary> /// Causes Validation /// </summary> [Category("Appearance")] [DefaultValue(false)] [Localizable(false)] public bool CausesValidation { get { if (ViewState[ViewStateConstants.CausesValidation.ToString()] == null) { ViewState[ViewStateConstants.CausesValidation.ToString()] = false; } return (bool)ViewState[ViewStateConstants.CausesValidation.ToString()]; } set { ViewState[ViewStateConstants.CausesValidation.ToString()] = value; btnDate.CausesValidation = value; } } #endregion #region Events /// <summary> /// A day was selected from the calendar control. /// </summary> public event EventHandler SelectionChanged; protected virtual void OnSelectionChanged() { if (SelectionChanged != null) // only raise the event if someone is listening. { SelectionChanged(this, EventArgs.Empty); } } #endregion #region Event Handlers /// <summary> /// The +/- button was clicked. /// </summary> protected void btnDate_Click(object sender, System.EventArgs e) { if (!calDate.Visible) { // expand the calendar calDate.Visible = true; txtDate.Enabled = false; btnDate.Text = CollapseButtonLabel; if (DateValue != DateTime.MinValue) { calDate.SelectedDate = DateValue; calDate.VisibleDate = DateValue; } } else { // collapse the calendar calDate.Visible = false; txtDate.Enabled = true; btnDate.Text = ExpandButtonLabel; } } /// <summary> /// A date was selected from the calendar. /// </summary> protected void calDate_SelectionChanged(object sender, System.EventArgs e) { calDate.Visible = false; txtDate.Visible = true; btnDate.Text = ExpandButtonLabel; txtDate.Enabled = true; txtDate.Text = calDate.SelectedDate.ToShortDateString(); OnSelectionChanged(); } #endregion /// <summary> /// Builds the contents of this control. /// </summary> protected override void CreateChildControls() { btnDate.Text = ExpandButtonLabel; btnDate.CausesValidation = CausesValidation; txtDate.ID = "txtDate"; calDate.Visible = false; if (ApplyDefaultStyle) { calDate.BackColor = System.Drawing.Color.White; calDate.BorderColor = System.Drawing.Color.FromArgb(10066329); calDate.CellPadding = 2; calDate.DayNameFormat = DayNameFormat.Shortest; calDate.Font.Name = "Verdana"; calDate.Font.Size = FontUnit.Parse("8pt"); calDate.ForeColor = System.Drawing.Color.Black; calDate.Height = new Unit(150, UnitType.Pixel); calDate.Width = new Unit(180, UnitType.Pixel); calDate.DayHeaderStyle.BackColor = System.Drawing.Color.FromArgb(228, 228, 228); calDate.DayHeaderStyle.Font.Size = FontUnit.Parse("7pt"); calDate.TitleStyle.Font.Bold = true; calDate.WeekendDayStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 204); } ConnectEventHandlers(); pnlCalendar.Controls.Add(calDate); pnlCalendar.Style["position"] = "absolute"; pnlCalendar.Style["filter"] = "alpha(opacity=95)"; pnlCalendar.Style["-moz-opacity"] = ".95"; pnlCalendar.Style["opacity"] = ".95"; pnlCalendar.Style["z-index"] = "2"; pnlCalendar.Style["background-color"] = "White"; if (CalendarPosition == CalendarDisplay.DisplayBelow) { pnlCalendar.Style["margin-top"] = "27px"; } else { pnlCalendar.Style["display"] = "inline"; } Controls.Add(txtDate); Controls.Add(pnlCalendar); Controls.Add(btnDate); base.CreateChildControls(); } /// <summary> /// Render the contents of this control. /// </summary> /// <param name="output">The HtmlTextWriter to use.</param> protected override void RenderContents(HtmlTextWriter output) { switch (CalendarPosition) { case CalendarDisplay.DisplayRight: { txtDate.RenderControl(output); btnDate.RenderControl(output); pnlCalendar.RenderControl(output); break; } case CalendarDisplay.DisplayBelow: { pnlCalendar.RenderControl(output); txtDate.RenderControl(output); btnDate.RenderControl(output); break; } } } /// <summary> /// Connect event handlers to events. /// </summary> private void ConnectEventHandlers() { btnDate.Click += new System.EventHandler(btnDate_Click); calDate.SelectionChanged += new System.EventHandler(calDate_SelectionChanged); } } } using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; [assembly: TagPrefix("DatePicker", "EWS")] namespace EclipseWebSolutions.DatePicker { [DefaultProperty("Text")] [ToolboxData("<{0}:DatePicker runat=server")] [DefaultEvent("SelectionChanged")] [ValidationProperty("TextValue")] public class DatePicker : WebControl, INamingContainer { #region Properties public TextBox txtDate = new TextBox(); public Calendar calDate = new Calendar(); public Button btnDate = new Button(); public Panel pnlCalendar = new Panel(); private enum ViewStateConstants { ValidationGroup, RegularExpression, ErrorMessage, RegExText, CalendarPosition, FormatString, ExpandLabel, CollapseLabel, ApplyDefaultStyle, CausesValidation, } /// <summary> /// Defines the available display modes of this calendar. /// </summary> public enum CalendarDisplay { DisplayRight, DisplayBelow } /// <summary> /// Where to display the popup calendar. /// </summary> [Category("Behaviour")] [Localizable(true)] public CalendarDisplay CalendarPosition { get { if (ViewState[ViewStateConstants.CalendarPosition.ToString()] == null) { ViewState[ViewStateConstants.CalendarPosition.ToString()] = CalendarDisplay.DisplayRight; } return (CalendarDisplay)ViewState[ViewStateConstants.CalendarPosition.ToString()]; } set { ViewState[ViewStateConstants.CalendarPosition.ToString()] = value; } } /// <summary> /// Text version of the control's value, for use by ASP.NET validators. /// </summary> public string TextValue { get { return txtDate.Text; } } /// <summary> /// Holds the current date value of this control. /// </summary> [Category("Behaviour")] [Localizable(true)] [Bindable(true, BindingDirection.TwoWay)] public DateTime DateValue { get { try { if (txtDate.Text == "") return DateTime.MinValue; DateTime val = DateTime.Parse(txtDate.Text); return val; } catch (ArgumentNullException) { return DateTime.MinValue; } catch (FormatException) { return DateTime.MinValue; } } set { if (value == DateTime.MinValue) { txtDate.Text = ""; } else { txtDate.Text = value.ToShortDateString(); } } } [Category("Behavior"), Themeable(false), DefaultValue("")] public virtual string ValidationGroup { get { if (ViewState[ViewStateConstants.ValidationGroup.ToString()] == null) { return string.Empty; } else { return (string)ViewState[ViewStateConstants.ValidationGroup.ToString()]; } } set { ViewState[ViewStateConstants.ValidationGroup.ToString()] = value; } } /// <summary> /// The label of the exand button. Shown when the calendar is hidden. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("PickDate")] [Localizable(true)] public string ExpandButtonLabel { get { String s = (String)ViewState[ViewStateConstants.ExpandLabel.ToString()]; return ((s == null) ? "PickDate" : s); } set { ViewState[ViewStateConstants.ExpandLabel.ToString()] = value; } } /// <summary> /// The label of the collapse button. Shown when the calendar is visible. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("Disabled")] [Localizable(true)] public string CollapseButtonLabel { get { String s = (String)ViewState[ViewStateConstants.CollapseLabel.ToString()]; return ((s == null) ? "Disabled" : s); } set { ViewState[ViewStateConstants.CollapseLabel.ToString()] = value; } } /// <summary> /// Whether to apply the default style. Disable this if you want to apply a custom style, or to use themes and skins /// to style the control. /// </summary> [Category("Appearance")] [DefaultValue(true)] [Localizable(true)] public bool ApplyDefaultStyle { get { if (ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] == null) { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = true; } return (bool)ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()]; } set { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = value; } } /// <summary> /// Causes Validation /// </summary> [Category("Appearance")] [DefaultValue(false)] [Localizable(false)] public bool CausesValidation { get { if (ViewState[ViewStateConstants.CausesValidation.ToString()] == null) { ViewState[ViewStateConstants.CausesValidation.ToString()] = false; } return (bool)ViewState[ViewStateConstants.CausesValidation.ToString()]; } set { ViewState[ViewStateConstants.CausesValidation.ToString()] = value; btnDate.CausesValidation = value; } } #endregion #region Events /// <summary> /// A day was selected from the calendar control. /// </summary> public event EventHandler SelectionChanged; protected virtual void OnSelectionChanged() { if (SelectionChanged != null) // only raise the event if someone is listening. { SelectionChanged(this, EventArgs.Empty); } } #endregion #region Event Handlers /// <summary> /// The +/- button was clicked. /// </summary> protected void btnDate_Click(object sender, System.EventArgs e) { if (!calDate.Visible) { // expand the calendar calDate.Visible = true; txtDate.Enabled = false; btnDate.Text = CollapseButtonLabel; if (DateValue != DateTime.MinValue) { calDate.SelectedDate = DateValue; calDate.VisibleDate = DateValue; } } else { // collapse the calendar calDate.Visible = false; txtDate.Enabled = true; btnDate.Text = ExpandButtonLabel; } } /// <summary> /// A date was selected from the calendar. /// </summary> protected void calDate_SelectionChanged(object sender, System.EventArgs e) { calDate.Visible = false; txtDate.Visible = true; btnDate.Text = ExpandButtonLabel; txtDate.Enabled = true; txtDate.Text = calDate.SelectedDate.ToShortDateString(); OnSelectionChanged(); } #endregion /// <summary> /// Builds the contents of this control. /// </summary> protected override void CreateChildControls() { btnDate.Text = ExpandButtonLabel; btnDate.CausesValidation = CausesValidation; txtDate.ID = "txtDate"; calDate.Visible = false; if (ApplyDefaultStyle) { calDate.BackColor = System.Drawing.Color.White; calDate.BorderColor = System.Drawing.Color.FromArgb(10066329); calDate.CellPadding = 2; calDate.DayNameFormat = DayNameFormat.Shortest; calDate.Font.Name = "Verdana"; calDate.Font.Size = FontUnit.Parse("8pt"); calDate.ForeColor = System.Drawing.Color.Black; calDate.Height = new Unit(150, UnitType.Pixel); calDate.Width = new Unit(180, UnitType.Pixel); calDate.DayHeaderStyle.BackColor = System.Drawing.Color.FromArgb(228, 228, 228); calDate.DayHeaderStyle.Font.Size = FontUnit.Parse("7pt"); calDate.TitleStyle.Font.Bold = true; calDate.WeekendDayStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 204); } ConnectEventHandlers(); pnlCalendar.Controls.Add(calDate); pnlCalendar.Style["position"] = "absolute"; pnlCalendar.Style["filter"] = "alpha(opacity=95)"; pnlCalendar.Style["-moz-opacity"] = ".95"; pnlCalendar.Style["opacity"] = ".95"; pnlCalendar.Style["z-index"] = "2"; pnlCalendar.Style["background-color"] = "White"; if (CalendarPosition == CalendarDisplay.DisplayBelow) { pnlCalendar.Style["margin-top"] = "27px"; } else { pnlCalendar.Style["display"] = "inline"; } Controls.Add(txtDate); Controls.Add(pnlCalendar); Controls.Add(btnDate); base.CreateChildControls(); } /// <summary> /// Render the contents of this control. /// </summary> /// <param name="output">The HtmlTextWriter to use.</param> protected override void RenderContents(HtmlTextWriter output) { switch (CalendarPosition) { case CalendarDisplay.DisplayRight: { txtDate.RenderControl(output); btnDate.RenderControl(output); pnlCalendar.RenderControl(output); break; } case CalendarDisplay.DisplayBelow: { pnlCalendar.RenderControl(output); txtDate.RenderControl(output); btnDate.RenderControl(output); break; } } } /// <summary> /// Connect event handlers to events. /// </summary> private void ConnectEventHandlers() { btnDate.Click += new System.EventHandler(btnDate_Click); calDate.SelectionChanged += new System.EventHandler(calDate_SelectionChanged); } } } <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" % <%@ Register Assembly="EclipseWebSolutions.DatePicker" Namespace="EclipseWebSolutions.DatePicker" TagPrefix="ews" % Untitled Page       using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void DatePicker1_SelectionChanged(object sender, EventArgs e) { Label1.Text = DatePicker1.DateValue.ToShortDateString(); pnlLabel.Update(); } }

    Read the article

  • What does "<<" mean in C#?

    - by Simon G
    Hi, Basically the questions in the title. I'm looking at the MVC 2 source code: public enum HttpVerbs { Get = 1 << 0, Post = 1 << 1, Put = 1 << 2, Delete = 1 << 3, Head = 1 << 4 } and I'm just curious as to what "<<" does. Thanks

    Read the article

< Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >