Search Results

Search found 1303 results on 53 pages for 'dr hydralisk'.

Page 6/53 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • 2D scene graph not transforming relative to parent

    - by Dr.Denis McCracleJizz
    I am currently in the process of coding my own 2D Scene graph, which is basically a port of flash's render engine. The problem I have right now is my rendering doesn't seem to be working properly. This code creates the localTransform property for each DisplayObject. Matrix m_transform = Matrix.CreateRotationZ(rotation) * Matrix.CreateScale(scaleX, scaleY, 1) * Matrix.CreateTranslation(new Vector3(x, y, z)); This is my render code. float dRotation; Vector2 dPosition, dScale; Matrix transform; transform = this.localTransform; if (parent != null) transform = localTransform * parent.localTransform; DecomposeMatrix(ref transform, out dPosition, out dRotation, out dScale); spriteBatch.Draw(this.texture, dPosition, null, Color.White, dRotation, new Vector2(originX, originY), dScale, SpriteEffects.None, 0.0f); Here is the result when I try to add the Stage then to the stage a First DisplayObjectContainer and then a second one. It may look fine but the problem lies in the fact that I add a first DisplayObjectContainer at (400,400) and the second one within it (that's the smallest one) at position (0,0). So he should be right over its parent but he gets render within the parent at the same position the parent has (400, 400) for some reason. It's just as if I double the parent's localMatrix and then render the second cat there. This is the code i use to loop through every childs. base.Draw(spriteBatch); foreach (DisplayObject childs in _childs) { childs.Draw(spriteBatch); }

    Read the article

  • Ubuntu touch on Nexus 4

    - by Dr. aNdRO
    I have finally managed to install the ubuntu touch on my nexus 4. Now the problem is its very Laggy. I have installed the "trusty" latest channel and its quite messy. Change background is not working. Dialer is really slow and everything is messed up. But I have seen many videos of nexus 4 and everything is working smoothly. So do I have to change to or pick any specific channel for installation? Please tell me is their any stable and properly working channel which I should choose for installation or what should I do?

    Read the article

  • C# public partial struct methods for more System.Windows.Media.Color

    - by dr d b karron
    How can I put in additional methods for manipulating color ? Best would be to overload the struct System.Windows.Media.Color. It is NOT a class (in c#). Now i'm tinkering with putting (in the same file for testing or must i put it in a different file) an namespace (Silverlight Application36 or System.Windows.Media ?) and a partial struct Color Normalize (double R, ...). I should see MyColor.Normalize() start being recognized by intellisense ? I'm not. I'm looking to put in a suite of overloaded color manipulations using floating and double numbers instead of unsigned byte integers. Any hints while I wack at it ? Cheers! dr.K

    Read the article

  • C# extern int ? How do I make a global var across classes and namespaces ?

    - by dr d b karron
    Dear C#'ers; As an old C/C++ programmer, I want to keep a global int counter across all of MY namespaces and classes. Public static extern int EventCount; Is not working; the VS2010 compiler won't let me have an extern int. Even with a DLLImport. [DllImport ( "SilverlightApplication37.dll" )] public static extern int EventCount; VS2010 complains Error 1 The modifier 'extern' is not valid for this item so how do i have a global int across all my code ? Cheers! dr.K

    Read the article

  • JqGrid addJSONData + ASP.NET 2.0 WS

    - by MilosC
    Dear community ! I am a bit lost. I' ve tried to implement a solution based on JqGrid and tried to use function as datatype. I've setted all by the book i guess, i get WS invoked and get JASON back, I got succes on clientside in ajaf call and i "bind" jqGrid using addJSONData but grid remains empty. I do not have any glue now... other "local" samples on same pages works without a problem (jsonstring ...) My WS method looks like : [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string GetGridData() { // Load a list InitSessionVariables(); SA.DB.DenarnaEnota.DenarnaEnotaDB db = new SAOP.SA.DB.DenarnaEnota.DenarnaEnotaDB(); DataSet ds = db.GetLookupForDenarnaEnota(SAOP.FW.DB.RecordStatus.All); // Turn into HTML friendly format GetGridData summaryList = new GetGridData(); summaryList.page = "1"; summaryList.total = "10"; summaryList.records = "160"; int i = 0; foreach (DataRow dr in ds.Tables[0].Rows) { GridRows row = new GridRows(); row.id = dr["DenarnaEnotaID"].ToString(); row.cell = "[" + "\"" + dr["DenarnaEnotaID"].ToString() + "\"" + "," + "\"" + dr["Kratica"].ToString() + "\"" + "," + "\"" + dr["Naziv"].ToString() + "\"" + "," + "\"" + dr["Sifra"].ToString() + "\"" + "]"; summaryList.rows.Add(row); } return JsonConvert.SerializeObject(summaryList); } my ASCX code is this: jQuery(document).ready(function(){ jQuery("#list").jqGrid({ datatype : function (postdata) { jQuery.ajax({ url:'../../AjaxWS/TemeljnicaEdit.asmx/GetGridData', data:'{}', dataType:'json', type: 'POST', contentType: "application/json; charset=utf-8", complete: function(jsondata,stat){ if(stat=="success") { var clearJson = jsondata.responseText; var thegrid = jQuery("#list")[0]; var myjsongrid = eval('('+clearJson+')'); alfs thegrid.addJSONData(myjsongrid.replace(/\\/g,'')); } } } ); }, colNames:['DenarnaEnotaID','Kratica', 'Sifra', 'Naziv'], colModel:[ {name:'DenarnaEnotaID',index:'DenarnaEnotaID', width:100}, {name:'Kratica',index:'Kratica', width:100}, {name:'Sifra',index:'Sifra', width:100}, {name:'Naziv',index:'Naziv', width:100}], rowNum:15, rowList:[15,30,100], pager: jQuery('#pager'), sortname: 'id', // loadtext:"Nalagam zapise...", // viewrecords: true, sortorder: "desc", // caption:"Vrstice", // width:"800", imgpath: "../Scripts/JGrid/themes/basic/images"}); }); from WS i GET JSON like this: {”page”:”1?,”total”:”10?,”records”:”160?,”rows”:[{"id":"18","cell":"["18","BAM","Konvertibilna marka","977"]“},{”id”:”19?,”cell”:”["19","RSD","Srbski dinar","941"]“},{”id”:”20?,”cell”:”["20","AFN","Afgani","971"]“},{”id”:”21?,”cell”:”["21","ALL","Lek","008"]“},{”id”:”22?,”cell”:”["22","DZD","Alžirski dinar","012"]“},{”id”:”23?,”cell”:”["23","AOA","Kvanza","973"]“},{”id”:”24?,”cell”:”["24","XCD","Vzhodnokaribski dolar","951"]“},{”id”:”25?,”cell”:” ……………… ["13","PLN","Poljski zlot","985"]“},{”id”:”14?,”cell”:”["14","SEK","Švedska krona","752"]“},{”id”:”15?,”cell”:”["15","SKK","Slovaška krona","703"]“},{”id”:”16?,”cell”:”["16","USD","Ameriški dolar","840"]“},{”id”:”17?,”cell”:”["17","XXX","Nobena valuta","000"]“},{”id”:”1?,”cell”:”["1","SIT","Slovenski tolar","705"]“}]} i have registered this js : clientSideScripts.RegisterClientScriptFile("prototype.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/prototype-1.6.0.2.js")); clientSideScripts.RegisterClientScriptFile("jquery.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/jquery.js")); clientSideScripts.RegisterClientScriptFile("jquery.jqGrid.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/jquery.jqGrid.js")); clientSideScripts.RegisterClientScriptFile("jqModal.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/js/jqModal.js")); clientSideScripts.RegisterClientScriptFile("jqDnR.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/js/jqDnR.js")); Basical i think it must be something stupid ...but i can figure it out now... Help wanted.

    Read the article

  • BPMN is dead, long live BPEL!

    - by JuergenKress
    “BPMN is dead, long live BPEL” was the title of our panel discussion during the SOA & BPM Integration Days 2011. At the JAXenter my discussion summery was just published (in German). If you want to learn more about SOA & BPM make sure you register for our up-coming conference October 12th & 13th 2011 in Düsseldorf. The speakers include the top SOA and BPM experts in Germany: Thilo Frotscher & Kornelius Fuhrer & Björn Hardegen & Nicolai Josuttis & Michael Kopp & Dr. Dirk Krafzig & Jürgen Kress & Frank Leymann & Berthold Maier & Hajo Normann & Max J. Pucher & Bernd Rücker & Dr. Gregor Scheithauer & Danilo Schmiedel & Guido Schmutz & Dirk Slama & Heiko Spindler & Volker Stiehl & Bernd Trops & Clemens Utschig-Utschig & Tammo van Lessen & Dr. Hendrik Voigt & Torsten Winterberg  For details please become a member in the SOA Partner Community for registration please visit  www.oracle.com/goto/emea/soa (OPN account required) Blog Twitter LinkedIn Mix Forum Wiki Website

    Read the article

  • Finding direction of travel in a world with wrapped edges

    - by crazy
    I need to find the shortest distance direction from one point in my 2D world to another point where the edges are wrapped (like asteroids etc). I know how to find the shortest distance but am struggling to find which direction it's in. The shortest distance is given by: int rows = MapY; int cols = MapX; int d1 = abs(S.Y - T.Y); int d2 = abs(S.X - T.X); int dr = min(d1, rows-d1); int dc = min(d2, cols-d2); double dist = sqrt((double)(dr*dr + dc*dc)); Example of the world : : T : :--------------:--------- : : : S : : : : : : T : : : :--------------: In the diagram the edges are shown with : and -. I've shown a wrapped repeat of the world at the top right too. I want to find the direction in degrees from S to T. So the shortest distance is to the top right repeat of T. but how do I calculate the direction in degreed from S to the repeated T in the top right? I know the positions of both S and T but I suppose I need to find the position of the repeated T however there more than 1. The worlds coordinates system starts at 0,0 at the top left and 0 degrees for the direction could start at West. It seems like this shouldn’t be too hard but I haven’t been able to work out a solution. I hope somone can help? Any websites would be appreciated.

    Read the article

  • Is there an excuse for short variable names?

    - by KChaloux
    This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent. For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows: double dR, dCV, dK, dDin, dDout, dRin, dRout dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1)); dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1)); ... and so on Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant: dR = radius dCV = curvature dK = conic constant dDin = inner aperture dDout = outer aperture dRin = inner radius dRout = outer radius I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

    Read the article

  • Is there an excuse for excessively short variable names?

    - by KChaloux
    This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent. For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows: double dR, dCV, dK, dDin, dDout, dRin, dRout dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1)); dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1)); ... and so on Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant: dR = radius dCV = curvature dK = conic constant dDin = inner aperture dDout = outer aperture dRin = inner radius dRout = outer radius I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

    Read the article

  • SQL Server 2008: FileStream Insertion Failure w/ .NET 3.5SP1

    - by James Alexander
    I've configured a db w/ a FileStream group and have a table w/ File type on it. When attempting to insert a streamed file and after I create the table row, my query to read the filepath out and the buffer returns a null file path. I can't seem to figure out why though. Here is the table creation script: /****** Object: Table [dbo].[JobInstanceFile] Script Date: 03/22/2010 18:05:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[JobInstanceFile]( [JobInstanceFileId] [int] IDENTITY(1,1) NOT NULL, [JobInstanceId] [int] NOT NULL, [File] [varbinary](max) FILESTREAM NULL, [FileId] [uniqueidentifier] ROWGUIDCOL NOT NULL, [Created] [datetime] NOT NULL, CONSTRAINT [PK_JobInstanceFile] PRIMARY KEY CLUSTERED ( [JobInstanceFileId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] FILESTREAM_ON [JobInstanceFilesGroup], UNIQUE NONCLUSTERED ( [FileId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] FILESTREAM_ON [JobInstanceFilesGroup] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[JobInstanceFile] ADD DEFAULT (newid()) FOR [FileId] GO Here's my proc I call to create the row before streaming the file: /****** Object: StoredProcedure [dbo].[JobInstanceFileCreate] Script Date: 03/22/2010 18:06:23 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO create proc [dbo].[JobInstanceFileCreate] @JobInstanceId int, @Created datetime as insert into JobInstanceFile (JobInstanceId, FileId, Created) values (@JobInstanceId, newid(), @Created) select scope_identity() GO And lastly, here's the code I'm using: public int CreateJobInstanceFile(int jobInstanceId, string filePath) { using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsumerMarketingStoreFiles"].ConnectionString)) using (var fileStream = new FileStream(filePath, FileMode.Open)) { connection.Open(); var tran = connection.BeginTransaction(IsolationLevel.ReadCommitted); try { //create the JobInstanceFile instance var command = new SqlCommand("JobInstanceFileCreate", connection) { Transaction = tran }; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@JobInstanceId", jobInstanceId); command.Parameters.AddWithValue("@Created", DateTime.Now); int jobInstanceFileId = Convert.ToInt32(command.ExecuteScalar()); //read out the filestream transaction context to stream the file for storage command.CommandText = "select [File].PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() from JobInstanceFile where JobInstanceFileId = @JobInstanceFileId"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@JobInstanceFileId", jobInstanceFileId); using (SqlDataReader dr = command.ExecuteReader()) { dr.Read(); //get the file path we're writing out to string writePath = dr.GetString(0); using (var writeStream = new SqlFileStream(writePath, (byte[])dr.GetValue(1), FileAccess.ReadWrite)) { //copy from one stream to another byte[] bytes = new byte[65536]; int numBytes; while ((numBytes = fileStream.Read(bytes, 0, 65536)) 0) writeStream.Write(bytes, 0, numBytes); } } tran.Commit(); return jobInstanceFileId; } catch (Exception e) { tran.Rollback(); throw e; } } } Can someone please let me know what I'm doing wrong. In the code, the following expression is returning null for the file path and shouldn't be: //get the file path we're writing out to string writePath = dr.GetString(0); The server is different then the computer the code is running on but the necessary shares appear to be in order and I have also run the following: EXEC sp_configure filestream_access_level, 2 Any help would be greatly appreciated. Thanks!

    Read the article

  • i don't solve "must declare a body because it is not marked abstract, extern, or partial" problem?

    - by programmerist
    How can i solve "must declare a body because it is not marked abstract, extern, or partial". This problem. Can you show me some advices? Full Error message is about Save, Update, Delete, Select events... Full message sample : GenoTip.DAL._AccessorForSQL.Save(string, System.Collections.Specialized.ListDictionary, System.Data.CommandType)' must declare a body because it is not marked abstract, extern, or partial This error also return in Update, Delete, Select... public abstract class _AccessorForSQL { public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType); public virtual bool Update(); public virtual bool Delete(); public virtual DataSet Select(); } class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { SqlConnection con = null; SqlCommand cmd = null; SqlDataReader dr = null; try { con = GetConnection(); cmd = new SqlCommand(sp, con); con.Open(); cmd.CommandType = cmdType; foreach (string ky in ld.Keys) { cmd.Parameters.AddWithValue(ky, ld[ky]); } dr = cmd.ExecuteReader(); ds = new DataSet(); dt = new DataTable(); ds.Tables.Add(dt); ds.Load(dr, LoadOption.OverwriteChanges, dt); } catch (Exception exp) { HttpContext.Current.Trace.Warn("Error in GetCustomerByID()", exp.Message, exp); } finally { if (dr != null) dr.Close(); if (con != null) con.Close(); } return (ds.Tables[0].Rows.Count 0) ? true : false; } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } private static SqlConnection GetConnection() { string connStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); return conn; }

    Read the article

  • How to call base abstract or interface from DAL into BLL?

    - by programmerist
    How can i access abstract class in BLL ? i shouldn't see GenAccessor in BLL it must be private class GenAccessor . i should access Save method over _AccessorForSQL. ok? MY BLL cs: public class AccessorForSQL: GenoTip.DAL._AccessorForSQL { public bool Save(string Name, string SurName, string Adress) { ListDictionary ld = new ListDictionary(); ld.Add("@Name", Name); ld.Add("@SurName", SurName); ld.Add("@Adress", Adress); return **base.Save("sp_InsertCustomers", ld, CommandType.StoredProcedure);** } } i can not access base.Save....???????? it is my DAL Layer: namespace GenoTip.DAL { public abstract class _AccessorForSQL { public abstract bool Save(string sp, ListDictionary ld, CommandType cmdType); public abstract bool Update(); public abstract bool Delete(); public abstract DataSet Select(); } private class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { SqlConnection con = null; SqlCommand cmd = null; SqlDataReader dr = null; try { con = GetConnection(); cmd = new SqlCommand(sp, con); con.Open(); cmd.CommandType = cmdType; foreach (string ky in ld.Keys) { cmd.Parameters.AddWithValue(ky, ld[ky]); } dr = cmd.ExecuteReader(); ds = new DataSet(); dt = new DataTable(); ds.Tables.Add(dt); ds.Load(dr, LoadOption.OverwriteChanges, dt); } catch (Exception exp) { HttpContext.Current.Trace.Warn("Error in GetCustomerByID()", exp.Message, exp); } finally { if (dr != null) dr.Close(); if (con != null) con.Close(); } return (ds.Tables[0].Rows.Count 0) ? true : false; } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } private static SqlConnection GetConnection() { string connStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); return conn; }

    Read the article

  • Login function runs different between local and server

    - by quangnd
    Here is my check login function: protected bool checkLoginStatus(String email, String password) { bool loginStatus = false; bool status = false; try { Connector.openConn(); String str = "SELECT * FROM [User]"; SqlCommand cmd = new SqlCommand(str, Connector.conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "tblUser"); //check valid foreach (DataRow dr in ds.Tables[0].Rows) { if (email == dr["Email"].ToString() && password == Connector.base64Decode(dr["Password"].ToString())) { Session["login_status"] = true; Session["username"] = dr["Name"].ToString(); Session["userId"] = dr["UserId"].ToString(); status = true; break; } } } catch (Exception ex) { } finally { Connector.closeConn(); } return status; } And call it at my aspx page: String email = Login1.UserName.Trim(); String password = Login1.Password.Trim(); if (checkLoginStatus(email, password)) Response.Redirect(homeSite); else lblFailure.Text = "Invalid!"; I ran this page at localhost successful! When I published it to server, this function only can run if email and password correct! Other, error occured: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) I tried open SQL Server 2008 Configuration Manager and enable SQL Server Browser service (Logon as:NT Authority/Local Service) but it stills error. (note: here is connection string of openConn() at Localhost (run on SQLEXpress 2005) connectionString="Data Source=MYLAPTOP\SQLEXPRESS;Initial Catalog=Spider_Vcms;Integrated Security=True" /> ) At server (run on SQL Server Enterprise 2008) connectionString="Data Source=SVR;Initial Catalog=Spider_Vcms;User Id=abc;password=123456;" /> anyone have an answer for my problem :( thanks a lot!

    Read the article

  • Using the latest (stable release) of Oracle Developer Tools for Visual Studio 11.1.0.7.20.

    - by mbcrump
    +  = Simple and safe Data connections.   This guide is for someone wanting to use the latest ODP.NET quickly without reading the official documentation. This guide will get you up and running in about 15 minutes. I have reviewed my referral link to my simple Setting up ODP.net with Win7 x64 and noticed most people were searching for one of the following terms: “how to use odp.net with vs” “setup connection odp.net” “query db using odp and vs” While my article provided links and a sample tnsnames.ora file, it really didn’t tell you how to use it. I’m hoping that this brief tutorial will help. So before we get started, you will need the following: Download the following: www.oracle.com/technology/software/tech/dotnet/utilsoft.html from oracle and install it. It is the first one on the page. Visual Studio 2008 or 2010. It should be noted that The System.Data.OracleClient namespace is the OLD .NET Framework Data Provider for Oracle. It should not be used anymore as it has been depreciated. The latest version which is what we are using is Oracle.DataAccess.Client. First things first, Add a reference to the Oracle.DataAccess.Client after you install ODP.NET   Copy and paste the following C# code into your project and replace the relevant info including the query string and you should be able to return data. I have commented several lines of code to assist in understanding what it is doing.   Lambda Expression. using System; using System.Data; using Oracle.DataAccess.Client;   namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {           try         {             //Setup DataSource             string oradb = "Data Source=(DESCRIPTION ="                                    + "(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521)))"                                    + "(CONNECT_DATA = (SERVICE_NAME = SERVICENAME))) ;"                                    + "Persist Security Info=True;User ID=USER;Password=PASSWORD;";                        //Open Connection to Oracle - this could be moved outside the try.             OracleConnection conn = new OracleConnection(oradb);             conn.Open();               //Create cmd and use parameters to prevent SQL injection attacks.             OracleCommand cmd = new OracleCommand();             cmd.Connection = conn;               cmd.CommandText = "select username from table where username = :username";               OracleParameter p1 = new OracleParameter("username", OracleDbType.Varchar2);             p1.Value = username;             cmd.Parameters.Add(p1);               cmd.CommandType = CommandType.Text;               OracleDataReader dr = cmd.ExecuteReader();             dr.Read();               //Contains the value of the datarow             Console.WriteLine(dr["username"].ToString());               //Disposes of objects.             dr.Dispose();             cmd.Dispose();             conn.Dispose();         }           catch (OracleException ex) // Catches only Oracle errors         {             switch (ex.Number)             {                 case 1:                     Console.WriteLine("Error attempting to insert duplicate data.");                     break;                 case 12545:                     Console.WriteLine("The database is unavailable.");                     break;                 default:                     Console.WriteLine(ex.Message.ToString());                     break;             }         }           catch (Exception ex) // Catches any error not previously caught         {                   Console.WriteLine("Unidentified Error: " + ex.Message.ToString());              }         }       }           } At this point, you should have a working Program that returns data from an oracle database. If you are still having trouble then drop me a line and I will be happy to assist. As of this writing, oracle has announced the latest beta release of ODP.NET 11.2.0.1.1 Beta.  This release includes .NET Framework 4 and .NET Framework 4 Client Profile support. You may want to hold off on this version for a while as its BETA, and I wouldn’t want any production code using any BETA software.

    Read the article

  • Ajax Autocomplete Extender

    - by Jason Ulloa
    El objetivo de este post es preparar un ejemplo sobre un tema que es planteado muy frecuentemente en los Foros de MSDN, como realizar un Autocomplete contra una base de datos. Qué requerimos? Antes de poder realizar un Autocomplete debemos tener en cuenta los elementos principales que requerimos para poder hacerlo funcionar, descritos de la siguiente manera: 1. Textbox: Nuestro grandioso amigo Textbox, que será donde el usuario ingresará los datos a buscar. 2. Un Webservice: que contendrá el método que se conectara a la base de datos y devolverá una lista con la información encontrada. 3. Ajax Autocomplete Extender: este es por decirlo así, el elemento más importante. Nos servirá como medio de enlace entre el webservice que expone el método y el textbox recuperando y mostrando los datos en forma de lista desplegable. La implementación Si bien parecierá complicado, crear un autocomplete extender es bastante sencillo. Empezaremos creando un nuevo sitio asp.net, en este sitio agregaremos un textbox y dos controles muy importantes de Ajax el ToolkitScriptManager para controlar el rende rizado de los script de ajax y el AutocompleteExtender que, como mencione anteriormente, será el medio de enlace. Antes de mostrar como quedará el código de lo anterior, explicaré algunas propiedades del AutocompleteExtender para que se entienda de mejor manera: 1. El ServicePath: contiene la ruta relativa al webservice que utilizaremos. 2. MinimumPrefixLength: se refiere al número de caracteres que deben ser digitados antes de iniciar la búsqueda. 3. ServiceMethod: el nombre del metodo de nuestro webservice que se encargará de devolver los datos. 4. EnableCaching: para mantener en cache los datos consultados, obteniendo mayor velocidad. 5. TargetControlID: una de las propiedades más importantes, acá se coloca el nombre del textbox al cual se unirá el Autocomplete 6. CompletionInterval: tiempo que debe transcurrir antes de iniciar con el trabajo de los datos. Una vez, explicadas las propiedades básicas, veamos como queda implementada la primer parte de nuestro autocomplete: <form id="form1" runat="server"> <div> <asp:ToolkitScriptManager ID="manager" runat="server" /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" ServicePath="WebService.asmx" MinimumPrefixLength="1" ServiceMethod="PersonasInfo " EnableCaching="true" TargetControlID="TextBox1" UseContextKey="True" CompletionSetCount="10" CompletionInterval="0"> </asp:AutoCompleteExtender> </div> </form>   Ahora que nuestro código html está completo, es hora de trabajar directamente con nuestro webservice, este deberá contener un método que devuelva una lista o arreglo de datos, los cuales por supuesto, serán traídos desde la base de datos. Antes de implementar este método, debemos asegurarnos de que nuestra clase del webservice tiene habilitados los espacios para ser utilizada [System.Web.Script.Services.ScriptService()] [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WebService : System.Web.Services.WebService {}   Ahora si, nuestro metodo principal [WebMethod()] [System.Web.Script.Services.ScriptMethod()] public string[] PersonasInfo(string prefixText, int count) { string connstring = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;   using (SqlConnection conn = new SqlConnection(connstring)) { SqlCommand comando = new SqlCommand("select nombre from personas where nombre LIKE '%' + @param + '%' ", conn); comando.Parameters.AddWithValue("@param", prefixText); SqlDataReader dr = default(SqlDataReader); comando.Connection.Open(); dr = comando.ExecuteReader(); List<string> items = new List<string>();   while (dr.Read()) { items.Add(dr["nombre"].ToString()); } comando.Connection.Close(); return items.ToArray(); } }   Del método anterior no explicaré en profundidad, pues es bastante sencillo. Una consulta a la base de datos utilizando un datareader y devolviendo los datos en una lista como arreglo. Lo más importante serían las 2 primeras líneas [WebMethod()] y el [ScriptMethod()] las cuales habilitan nuestro método para poder ser accedido y utilizado. Por último, el código de ejemplo en C# (VB Autcomplete):

    Read the article

  • Multiple asynchronous method calls to method while in a loop

    - by ranabra
    I have spent a whole day trying various ways using 'AddOnPreRenderCompleteAsync' and 'RegisterAsyncTask' but no success so far. I succeeded making the call to the DB asynchronous using 'BeginExecuteReader' and 'EndExecuteReader' but that is missing the point. The asynch handling should not be the call to the DB which in my case is fast, it should be afterwards, during the 'while' loop, while calling an external web-service. I think the simplified pseudo code will explain best: (Note: the connection string is using 'MultipleActiveResultSets') "Select ID, UserName from MyTable" 'Open connection to DB ExecuteReader(); if (DR.HasRows) {     while (DR.Read())     {         'Call external web-service         'and get current Temperature of each UserName - DR["UserName"].ToString()         'Update my local DB         Update MyTable set Temperature = ValueFromWebService where UserName =                                       DR["UserName"]         CmdUpdate.ExecuteNonQuery();     }     'Close connection etc } Accessing the DB is fast. Getting the returned result from the external web-service is slow and that at least should be handled Asynchnously. If each call to the web service takes just 1 second, assuming I have only 100 users it will take minimum 100 seconds for the DB update to complete, which obviously is not an option. There eventually should be thousands of users (currently only 2). Currently everything works, just very synchnously :) Thoughts to myself: Maybe my way of approaching this is wrong? Maybe the entire process should be called Asynchnously Many thanx

    Read the article

  • Problem: Sorting for GridView/ObjectDataSource changes depending on page

    - by user148298
    I have a GridView tied to an ObjectDataSource using paging. The paging works fine, except that the sort order changes depending on which page of the results is being viewed. This causes items to reappear on subsequent pages among other issues. I traced the problem to my DAL, which reads a page at a time and then sorts it. Obviously the sorting is going to change as the result set size changes. Is there an improvement to this algorithm. I would like to use a datareader if possible: [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)] public static WordsCollection LoadForCriteria(string sqlCriteria, int maximumRows, int startRowIndex, string sortExpression) { //DEFAULT SORT EXPRESSION if (string.IsNullOrEmpty(sortExpression)) sortExpression = "OrderBy"; //CREATE THE DYNAMIC SQL TO LOAD OBJECT StringBuilder selectQuery = new StringBuilder(); selectQuery.Append("SELECT"); if (maximumRows > 0) selectQuery.Append(" TOP " + (startRowIndex + maximumRows).ToString()); selectQuery.Append(" " + Words.GetColumnNames(string.Empty)); selectQuery.Append(" FROM sw_Words"); string whereClause = string.IsNullOrEmpty(sqlCriteria) ? string.Empty : " WHERE " + sqlCriteria; selectQuery.Append(whereClause); selectQuery.Append(" ORDER BY " + sortExpression); Database database = Token.Instance.Database; DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()); //EXECUTE THE COMMAND WordsCollection results = new WordsCollection(); int thisIndex = 0; int rowCount = 0; using (IDataReader dr = database.ExecuteReader(selectCommand)) { while (dr.Read() && ((maximumRows < 1) || (rowCount < maximumRows))) { if (thisIndex >= startRowIndex) { Words varWords = new Words(); Words.LoadDataReader(varWords, dr); results.Add(varWords); rowCount++; } thisIndex++; } dr.Close(); } return results; }

    Read the article

  • How can I read a DBF file with incorrectly defined column data types using ADO.NET?

    - by Jason
    I have a several DBF files generated by a third party that I need to be able to query. I am having trouble because all of the column types have been defined as characters, but the data within some of these fields actually contain binary data. If I try to read these fields using an OleDbDataReader as anything other than a string or character array, I get an InvalidCastException thrown, but I need to be able to read them as a binary value or at least cast/convert them after they are read. The columns that actually DO contain text are being returned as expected. For example, the very first column is defined as a character field with a length of 2 bytes, but the field contains a 16-bit integer. I have written the following test code to read the first column and convert it to the appropriate data type, but the value is not coming out right. The first row of the database has a value of 17365 (0x43D5) in the first column. Running the following code, what I end up getting is 17215 (0x433F). I'm pretty sure it has to do with using the ASCII encoding to get the bytes from the string returned by the data reader, but I'm not sure of another way to get the value into the format that I need, other that to write my own DBF reader and bypass ADO.NET altogether which I don't want to do unless I absolutely have to. Any help would be greatly appreciated. byte[] c0; int i0; string con = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ASTM;Extended Properties=dBASE III;User ID=Admin;Password=;"; using (OleDbConnection c = new OleDbConnection(con)) { c.Open(); OleDbCommand cmd = c.CreateCommand(); cmd.CommandText = "SELECT * FROM astm2007"; OleDbDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { c0 = Encoding.ASCII.GetBytes(dr.GetValue(0).ToString()); i0 = BitConverter.ToInt16(c0, 0); } dr.Dispose(); }

    Read the article

  • Procedure or function AppendDataCT has too many arguments specified

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server website application. I am a newbie to ASP.NET. I am getting the above compiler error. Can you give me advice on how to fix this? Code snippet: public static string AppendDataCT(DataTable dt, Dictionary<int, string> dic) { string connString = ConfigurationManager.ConnectionStrings["AW3_string"].ConnectionString; string errorMsg; try { SqlConnection conn2 = new SqlConnection(connString); SqlCommand cmd = conn2.CreateCommand(); cmd.CommandText = "dbo.AppendDataCT"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; SqlParameter p1, p2, p3; foreach (string s in dt.Rows[1].ItemArray) { DataRow dr = dt.Rows[1]; // second row p1 = cmd.Parameters.AddWithValue((string)dic[0], (string)dr[0]); p1.SqlDbType = SqlDbType.VarChar; p2 = cmd.Parameters.AddWithValue((string)dic[1], (string)dr[1]); p2.SqlDbType = SqlDbType.VarChar; p3 = cmd.Parameters.AddWithValue((string)dic[2], (string)dr[2]); p3.SqlDbType = SqlDbType.VarChar; } conn2.Open(); cmd.ExecuteNonQuery(); It errors on this last line here. And here is that SP: ALTER PROCEDURE [dbo].[AppendDataCT] @col1 VARCHAR(50), @col2 VARCHAR(50), @col3 VARCHAR(50) AS BEGIN SET NOCOUNT ON; DECLARE @TEMP DATETIME SET @TEMP = (SELECT CONVERT (DATETIME, @col3)) INSERT INTO Person.ContactType (Name, ModifiedDate) VALUES( @col2, @TEMP) END

    Read the article

  • How to pass a value from a method to property procedure in c#?

    - by sameer
    Here is my code: The jewellery class is my main class in which i am inheriting a connection string class. class Jewellery : Connectionstr { string lmcode; public string LM_code/**/Here i want to access the value of the method ReadData i.e displaystring and i want to store this value in the insert query below.** { get { return lmcode; } set { lmcode = value; } } string mname; public string M_Name { get { return mname; } set { mname = value; } } string desc; public string Desc { get { return desc; } set { desc = value; } } public string ReadData() { OleDbDataReader dr; string jid = string.Empty; string displayString = string.Empty; String query = "select max(LM_code)from Master_Accounts"; Datamanager.RunExecuteReader(Constr, query); if (dr.Read()) { jid = dr[0].ToString(); if (string.IsNullOrEmpty(jid)) { jid = "AM0000"; } int len = jid.Length; string split = jid.Substring(2, len - 2); int num = Convert.ToInt32(split); num++; displayString = jid.Substring(0, 2) + num.ToString("0000"); dr.Close(); } **return displayString;** I want to pass this value to the above property procedure above i.e LM_code. } public void add() { String query ="insert into Master_Accounts values ('" + LM_code + "','" + M_Name + "'," + "'" + Desc + "')"; Datamanager.RunExecuteNonQuery(Constr , query);// } If possible can u edit this code! Anticipated thanks by sameer

    Read the article

  • Bind SQLiteDataReader to GridView in ASP.NET

    - by Charles Gargent
    Hi, this is all rather new to me, but I have searched for a good while and cant find any idea why I cant get this to work, dr looks like it is populated but I get this nullreferenceexeception when I try to bind to the gridview Thanks code SQLiteConnection cnn = new SQLiteConnection(@"Data Source=c:\log.db"); cnn.Open(); SQLiteCommand cmd = new SQLiteCommand(@"SELECT * FROM evtlog", cnn); SQLiteDataReader dr = cmd.ExecuteReader(); GridView1.DataSource = dr; GridView1.DataBind(); dr.Close(); cnn.Close(); Codebehind <asp:ContentPlaceHolder ID="MainContent" runat="server"> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </asp:ContentPlaceHolder> error Object reference not set to an instance of an object. at WPKG_Report.SiteMaster.Button1_Click(Object sender, EventArgs e) in C:\Projects\Report\Site.Master.cs:line 32 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

    Read the article

  • Binding ListBox ItemCount to IvalueConverter

    - by Ben
    Hi All, I am fairly new to WPF so forgive me if I am missing something obvious. I'm having a problem where I have a collection of AggregatedLabels and I am trying to bind the ItemCount of each AggregatedLabel to the FontSize in my DataTemplate so that if the ItemCount of an AggregatedLabel is large then a larger fontSize will be displayed in my listBox etc. The part that I am struggling with is the binding to the ValueConverter. Can anyone assist? Many thanks! XAML Snippet <DataTemplate x:Key="TagsTemplate"> <WrapPanel> <TextBlock Text="{Binding Name, Mode=Default}" TextWrapping="Wrap" FontSize="{Binding ItemCount, Converter={StaticResource CountToFontSizeConverter}, Mode=Default}" Foreground="#FF0D0AF7"/> </WrapPanel> </DataTemplate> <ListBox x:Name="tagsList" ItemsSource="{Binding AggregatedLabels, Mode=Default}" ItemTemplate="{StaticResource TagsTemplate}" Style="{StaticResource tagsStyle}" Margin="200,10,16.171,11.88" /> AggregatedLabel Collection using (DB2DataReader dr = command.ExecuteReader()) { while (dr.Read()) { AggregatedLabelModel aggLabel = new AggregatedLabelModel(); aggLabel.ID = Convert.ToInt32(dr["LABEL_ID"]); aggLabel.Name = dr["LABEL_NAME"].ToString(); LabelData.Add(aggLabel); } } Converter public class CountToFontSizeConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { const int minFontSize = 6; const int maxFontSize = 38; const int increment = 3; int count = (int)value; if ((minFontSize + count + increment) < maxFontSize) { return minFontSize + count + increment; } return maxFontSize; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } AggregatedLabel Class public class AggregatedLabelModel { public int ID { get; set; } public string Name { get; set; } } CollectionView ListCollectionView labelsView = new ListCollectionView(LabelData); labelsView.GroupDescriptions.Add(new PropertyGroupDescription("Name"));

    Read the article

  • Escape Quote in C# for javascript consumption

    - by Jason
    I have a ASP.Net web handler that returns results of a query in JSON format public static String dt2JSON(DataTable dt) { String s = "{\"rows\":["; if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { s += "{"; for (int i = 0; i < dr.Table.Columns.Count; i++) { s += "\"" + dr.Table.Columns[i].ToString() + "\":\"" + dr[i].ToString() + "\","; } s = s.Remove(s.Length - 1, 1); s += "},"; } s = s.Remove(s.Length - 1, 1); } s += "]}"; return s; } The problem is that sometimes the data returned has quotes in it and I would need to javascript-escape these so that it can be properly created into a js object. I need a way to find quotes in my data (quotes aren't there every time) and place a "/" character in front of them. Example response text (wrong): {"rows":[{"id":"ABC123","length":"5""}, {"id":"DEF456","length":"1.35""}, {"id":"HIJ789","length":"36.25""}]} I would need to escape the " so my response should be: {"rows":[{"id":"ABC123","length":"5\""}, {"id":"DEF456","length":"1.35\""}, {"id":"HIJ789","length":"36.25\""}]} Also, I'm pretty new to C# (coding in general really) so if something else in my code looks silly let me know.

    Read the article

  • using the ASP.NET Caching API via method annotations in C#

    - by craigmoliver
    In C#, is it possible to decorate a method with an annotation to populate the cache object with the return value of the method? Currently I'm using the following class to cache data objects: public class SiteCache { // 7 days + 6 hours (offset to avoid repeats peak time) private const int KeepForHours = 174; public static void Set(string cacheKey, Object o) { if (o != null) HttpContext.Current.Cache.Insert(cacheKey, o, null, DateTime.Now.AddHours(KeepForHours), TimeSpan.Zero); } public static object Get(string cacheKey) { return HttpContext.Current.Cache[cacheKey]; } public static void Clear(string sKey) { HttpContext.Current.Cache.Remove(sKey); } public static void Clear() { foreach (DictionaryEntry item in HttpContext.Current.Cache) { Clear(item.Key.ToString()); } } } In methods I want to cache I do this: [DataObjectMethod(DataObjectMethodType.Select)] public static SiteSettingsInfo SiteSettings_SelectOne_Name(string Name) { var ck = string.Format("SiteSettings_SelectOne_Name-Name_{0}-", Name.ToLower()); var dt = (DataTable)SiteCache.Get(ck); if (dt == null) { dt = new DataTable(); dt.Load(ModelProvider.SiteSettings_SelectOne_Name(Name)); SiteCache.Set(ck, dt); } var info = new SiteSettingsInfo(); foreach (DataRowView dr in dt.DefaultView) info = SiteSettingsInfo_Load(dr); return info; } Is it possible to separate those concerns like so: (notice the new annotation) [CacheReturnValue] [DataObjectMethod(DataObjectMethodType.Select)] public static SiteSettingsInfo SiteSettings_SelectOne_Name(string Name) { var dt = new DataTable(); dt.Load(ModelProvider.SiteSettings_SelectOne_Name(Name)); var info = new SiteSettingsInfo(); foreach (DataRowView dr in dt.DefaultView) info = SiteSettingsInfo_Load(dr); return info; }

    Read the article

  • Perl Regex - Condensing groups of find/replace

    - by brydgesk
    I'm using Perl to perform some file cleansing, and am running into some performance issues. One of the major parts of my code involves standardizing name fields. I have several sections that look like this: sub substitute_titles { my ($inStr) = @_; ${$inStr} =~ s/ PHD./ PHD /; ${$inStr} =~ s/ P H D / PHD /; ${$inStr} =~ s/ PROF./ PROF /; ${$inStr} =~ s/ P R O F / PROF /; ${$inStr} =~ s/ DR./ DR /; ${$inStr} =~ s/ D.R./ DR /; ${$inStr} =~ s/ HON./ HON /; ${$inStr} =~ s/ H O N / HON /; ${$inStr} =~ s/ MR./ MR /; ${$inStr} =~ s/ MRS./ MRS /; ${$inStr} =~ s/ M R S / MRS /; ${$inStr} =~ s/ MS./ MS /; ${$inStr} =~ s/ MISS./ MISS /; } I'm passing by reference to try and get at least a little speed, but I fear that running so many (literally hundreds) of specific string replaces on tens of thousands (likely hundreds of thousands eventually) of records is going to hurt the performance. Is there a better way to implement this kind of logic than what I'm doing currently? Thanks Edit: Quick note, not all the replace functions are just removing periods and spaces. There are string deletions, soundex groups, etc.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >