Daily Archives

Articles indexed Friday December 14 2012

Page 8/17 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • vbsript and excel delete all worksheets except last one

    - by matthew moore
    I am trying to delete all worksheet in excel exept last one and save it then move its location. I can not get it took work as it deletes all other worksheets but errors out with and out of range error. Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.DisplayAlerts = False Set objWorkbook = objExcel.Workbooks.Open("C:\M-tek 10-31-12_Tony.xlsx") i = objWorkbook.Worksheets.Count Do while i = i i = i - 1 objWorkbook.Worksheets(i).Delete Loop

    Read the article

  • php multidimensional array if loop

    - by user1091558
    I have a multidimensional array like this array[value][1][1] Now i would like to implement if loop like this if ($value = array[value][1][1]) { echo "It works"; } Now it works if i assign the values like [1][1],[2][1]. Is it possible to compare the whole array. I mean if the array looks like array[value][1][1],array[value][2][1],..........,array[value][n][1] It works should be echoed. I tried like this. if ($value = array[value][][]) { echo "It works"; } But its not working. Can anyone give me the correct syntax?

    Read the article

  • Windows 8 Set User Account Image

    - by Nexion
    I'm trying to write a small CONSOLE (not metro style) app to quickly change the user account image of the current user to a select image for a setup scrip that I'm running on a bunch of laptops. They're all Windows 8 and (since it hasn't been out terribly long) I can't find a ton of info on it. I did manage to figure out that you need to use the Windows.System.UserProfile object to do so, but I can't find any documentation on how to do so in a console app. Thoughts? Suggestions?

    Read the article

  • Is it possible to filter data used by pivot table based on filtering the rows in a source table in Excel?

    - by Geoffrey Stoel
    I have developed a dashboard in Excel 2007 that uses one source table in a sheet (being filled with a query on our data warehouse) and multiple pivot tables making different cross sections on this data. I use the GETPIVOTDATA in almost a hundred formulas to give me the right value for a specific indicator in my dashboard. This all works fine. However I now have received the question to make the dashboard for 5 different segments. As you can imagine I don't want to create 5 different workbooks for this and need to maintain the dashboard logic on all of them. So my question is the following. Is it possible to automatically (through VBA or any other means) filter the results in my source table which is the source for my pivot tables and thus for my dashboard values. So schematically: DATABASE_VIEW -- SOURCE_TABLE -- 12 pivot tables -- 100 GETPIVOTDATA functions Preferably I would like to load all the segments in the source_table (one view on my database) and then filter the data in the source table, which results in filterd source_dat for my pivots. This way I can (without requerying the db) quickly change between segments in the dashboards (refreshing pivots only). Data in the source table has the column: CUSTOMER_SEGMENT available to filter upon. Any help is appreciated. Geoffrey

    Read the article

  • SqlDataAdapter Update is not working in C# wih Sql Server

    - by Ahmed
    I am trying to save data from C# form to Sql server Northwind Orders database, I am only using CustomerID, OrderDate and ShippedDate for data entry. Following is the code to Form load and save button: private void Form1_Load(object sender, EventArgs e) { SetComb(); connectionString = ConfigurationManager.AppSettings["connectionString"]; sqlConnection = new SqlConnection(connectionString); String sqlSelect = "Select OrderID, CustomerID, OrderDate, ShippedDate from Orders"; sqlDataMaster = new SqlDataAdapter(sqlSelect, sqlConnection); sqlConnection.Open(); //=============================================================================== //--- Set up the INSERT Command //=============================================================================== sInsProcName = "prInsert_Order"; insertcommand = new SqlCommand(sInsProcName, sqlConnection); insertcommand.CommandType = CommandType.StoredProcedure; insertcommand.Parameters.Add(new SqlParameter("@nNewID", SqlDbType.Int, 0, ParameterDirection.Output, false, 0, 0, "OrderID", DataRowVersion.Default, null)); insertcommand.UpdatedRowSource = UpdateRowSource.OutputParameters; insertcommand.Parameters.Add(new SqlParameter("@sCustomerID", SqlDbType.NChar, 5,"CustomerID")); insertcommand.Parameters["@sCustomerID"].Value = cmbCust.SelectedValue; insertcommand.Parameters.Add(new SqlParameter("@dtOrderDate", SqlDbType.DateTime, 8,"OrderDate")); insertcommand.Parameters["@dtOrderDate"].Value = dtOrdDt.Text; insertcommand.Parameters.Add(new SqlParameter("@dtShipDate", SqlDbType.DateTime, 8,"ShippedDate")); insertcommand.Parameters["@dtShipDate"].Value = dtShipDt.Text; sqlDataMaster.InsertCommand = insertcommand; //=============================================================================== //--- Set up the UPDATE Command //=============================================================================== sUpdProcName = "prUpdate_Order"; updatecommand = new SqlCommand(sUpdProcName, sqlConnection); updatecommand.CommandType = CommandType.StoredProcedure; updatecommand.Parameters.Add(new SqlParameter("@nOrderID", SqlDbType.Int, 4, "OrderID")); updatecommand.Parameters.Add(new SqlParameter("@dtOrderDate", SqlDbType.DateTime, 8, "OrderDate")); updatecommand.Parameters.Add(new SqlParameter("@dtShipDate", SqlDbType.DateTime, 8, "ShippedDate")); sqlDataMaster.UpdateCommand = updatecommand; //=============================================================================== //--- Set up the DELETE Command //=============================================================================== sDelProcName = "prDelete_Order"; deletecommand = new SqlCommand(sDelProcName, sqlConnection); deletecommand.CommandType = CommandType.StoredProcedure; deletecommand.Parameters.Add(new SqlParameter("@nOrderID", SqlDbType.Int, 4, "OrderID")); sqlDataMaster.DeleteCommand = deletecommand; dt = new DataTable(); sqlDataMaster.FillSchema(dt, SchemaType.Source); ds = new DataSet(); ds.Tables.Add(dt); bs = new BindingSource(); bs.DataSource = ds.Tables[0]; } public void SetComb() { cmbCust.DataSource = dm.GetData("Select * from Customers order by CompanyName"); cmbCust.DisplayMember = "CompanyName"; cmbCust.ValueMember = "CustomerId"; cmbCust.Text = ""; } private void btnSave_Click(object sender, EventArgs e) { sqlDataMaster.Update((DataTable) bs.DataSource); } and Stored Procedures for Insert/Update/Delete set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[prInsert_Order] -- ALTER PROCEDURE prInsert_Order @sCustomerID CHAR(5), @dtOrderDate DATETIME, @dtShipDate DATETIME, @nNewID INT OUTPUT AS SET NOCOUNT ON INSERT INTO Orders (CustomerID, OrderDate, ShippedDate) VALUES (@sCustomerID, @dtOrderDate, @dtShipDate) SELECT @nNewID = SCOPE_IDENTITY() set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[prUpdate_Order] -- ALTER PROCEDURE prUpdate_Order @nOrderID INT, @dtOrderDate DATETIME, @dtShipDate DATETIME AS UPDATE Orders SET OrderDate = @dtOrderDate, ShippedDate = @dtShipDate WHERE OrderID = @nOrderID set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[prDelete_Order] -- ALTER PROCEDURE prDelete_Order @nOrderID INT AS DELETE Orders WHERE OrderID = @nOrderID In the form CustomerID is selected via combobox which has Display property of CustomerName and Value property of CustomerID. But when clicking save button it shows no error, but it also don't save anything in Orders Table of Northwind....dm.GetData is the method of my Data Access Layer class to just get the info and populate CustomerID combobox. Any help with the code is highly appreciated... Thanks Ahmed

    Read the article

  • What's the correct way to POST a compressed JSON string with RestSharp?

    - by Steve Dunn
    I want to use RestSharp to POST something somewhere. I'm posting straight JSON (and not POCOs). Because I'm posting plain JSON, I believe I need to use this workaround instead of setting Body: request.AddParameter( "application/json", myJsonString, ParameterType.RequestBody); This works fine when I'm not compressing the JSON. When I do, using this: request.Headers.Add("Content-Encoding", "gzip"); request.AddParameter( "application/json", GZipStream.CompressString(myJsonString), ParameterType.RequestBody); This doesn't work. I stepped through the code and in RestClient::ConfigureHttp, I see: http.RequestBody = body.Value.ToString(); Since I'm giving at a byte array, body.Value is set to System.Byte[] Is there a way for RestSharp to handle a gzipped json string in a POST request?

    Read the article

  • Jquery Ajax not receiving php response correctly

    - by Theo
    I'm sending a JSON response from php to jquery: foreach ( $obj as $o ) { $a[ $o->key] = utf8_encode($o->id); } die(json_encode($a)); my html/jquery code is: $.ajax({ type:'POST', url: "imoveis/carrega_bairros", data: ({cidade:10}), dataType:"json", success: function(ret) { alert(ret) if(ret.success) { // ... } else alert("error"); } }); The json response is perfect (i get it on the console), but jquery is receiving a NULL ret object and it alerts "error". What's the problem???

    Read the article

  • limiting a query to a specific item

    - by Dev-Ria
    I have a db with thousands of domains and data. I want to list only 100 rows of each domain. i can't use LIMIT 100 cause that only limits 100 records but I want dom1 to list 100 dom2 to list 100 dom3 to list 100 all in one query. This is what I have so far. SELECT domain COUNT(Key) AS DomCount FROM table_domain GROUP BY user,location ORDER BY domain,DomCount DESC Could I use a CASE?

    Read the article

  • My IF statement is changing variables in PHP

    - by user1902509
    I am fairly new to the whole programming thing, so forgive me if this is a stupid question. It seems odd that I haven't run into it before. I am trying to make an order form for a cake. You fill out the form, submit it, and it will then display the order in a new window, where you then hit "submit," and upload it to the Database. I have a series of If Statements to check for errors in the form before submitting it. Here is a simplified version of the code. Writing means any writing you want on the cake, Name is your name, and cake is what type of cake you want (the default is "None"). try { $name = trim($params->name); $cake = trim($params->cake); $writing = trim($params->writing); if (strlen($name) < 3){ throw new Exception("Please enter Your name."); } if ($cake = "None") { throw new Exception("Please select a Cake" } if ($cake = "Caramel Apple Pie" or $cake = "Pumpkin Pie" or $cake = "Eggnog Pie" and strlen($writing) > 1) { throw new Exception("We are sorry, but you can't write on any of our specialty pies."); } } catch(Exception $x) { $error = $x->getmessage(); } So what is happening is that when I go and hit submit the first time, the correct cake type comes up, but when you submit it the second time, the error comes up saying that I have "None" selected. All the other values are there and remain the same. I think the problem is that the first "IF" statement (Where it says "If($cake = "None")) is automatically changing $cake to "None" because I have tried commenting just that statement out, and it will then change the cake to be "Caramel Apple Pie," which is in the top of the next IF statement. Anyone know why it is doing this? And how to fix it?

    Read the article

  • Java complex validation in Dropwizard?

    - by miku
    I'd like to accept JSON on an REST endpoint and convert it to the correct type for immediate validation. The endpoint looks like this: @POST public Response createCar(@Valid Car car) { // persist to DB // ... } But there are many subclasses of Car, e.g. Van, SelfDrivingCar, RaceCar, etc. How could I accept the different JSON representations on the endpoint, while keeping the validation code in the Resource as concise as something like @Valid Car car? Again: I send in JSON like (here, it's the representation of a subclass of Car, namely SelfDrivingCar): { "id" : "t1", // every Car has an Id "kind" : "selfdriving", // every Car has a type-hint "max_speed" : "200 mph", // some attribute "ai_provider" : "fastcarsai ltd." // this is SelfDrivingCar-specific } and I'd like the validation machinery look into the kind attribute, create an instance of the appropriate subclass, here e.g. SelfDrivingCar and perform validation. I know I could create different endpoints for all kind of cars, but thats does not seem DRY. And I know that I could use a real Validator instead of the annotation and do it by hand, so I'm just asking if there's some elegant shortcut for this problem.

    Read the article

  • how to execute any function in jquery after few seconds on the click of any link

    - by james Bond
    I have struts2 jquery grid where on click of a row I am calling a jQuery function for performating a struts2 action. My code is running fine. I want to perform my jQuery function after delay of a few seconds. How can I do this? <script type="text/javascript"> //assume this code is working fine on rowselect from my jquery grid, New Updation in it is "i want to execute or load the url after few seconds" $(function(){ $.subscribe('rowselect', function(event,data) { var param = (event.originalEvent.id); $("#myAdvanceDivBoxx").load('<s:url action='InsertbooksToSession' namespace='/admin/setups/secure/jspHomepage/bookstransaction'/>'+"?bid="+event.originalEvent.id); }); }); </script> What i tried is the below code but am unable to get the output which i am looking for: <script type="text/javascript"> $(function(){ $.subscribe('rowselect', function(event,data) { var param = (event.originalEvent.id); $("#myAdvanceDivBoxx").load('<s:url action='InsertbooksToSession' namespace='/admin/setups/secure/jspHomepage/bookstransaction'/>'+"?bid="+event.originalEvent.id); }).delay(9000); }); </script>

    Read the article

  • Batch convert Malformed PDFs to TIF on Linux

    - by Mike Driscoll
    I need to convert a multipage PDF to TIF, but it appears to be a malformed PDF provided by our client. I tried using ImageMagick and GhostScript, but they do not convert the file correctly. The result is only about 85-90% correct. The only thing I've found that appears to do the job is GIMP, but I can't find an example to use it via its Batch Processing methods for PDFs. Here are the warnings I get from ImageMagick and GhostScript: **** Warning: Tf refers to an unknown resource name: FORMS$.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: P06BOB.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN308E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: P06BOB.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN308E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: P06BOB.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN308E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN307A.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN104A.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN308E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN208E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN308E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN208E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: HE14BP.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN208E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN106E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN208E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN106E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN208E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: HE08BP.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: HE11BP.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: AR10NP.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN308E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: JIMP2.l Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: HS11C.l Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: FORMS$.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN104A.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN208E.f Assuming it's a font name. **** Warning: Tf refers to an unknown resource name: UN307E.f Assuming it's a font name. **** This file had errors that were repaired or ignored. **** Please notify the author of the software that produced this **** file that it does not conform to Adobe's published PDF **** specification. I'm open to other suggestions too. Thanks!

    Read the article

  • shell script array length

    - by Dipro Sen
    I assume arguments to my shell scripts willbe ./x.sh subject N file1 file2 fileN So I am splicing argv from 3 till end candidates=${@:3} now I want to check whether length of candidates is same as given N I am trying with echo $((${#candidates[@]})) which is always returning 1. I can do echo "$#-2" | bc but, I shouldn't I be able to get array size ? I can use bc to do integer comparison. but I've to know the size of `candidates array which I am not getting properly.

    Read the article

  • Designing a recipe database that needs to include ingredients as well as sub-recipes

    - by VinceL
    I am designing a recipe database that needs to be very flexible as it is going to be communicating directly with our back-of-house inventory system. This is what I have so far in regards to the tables: Recipe: this table will contain the recipe date: the name, steps needed to cook, etc. Ingredients/Inventory: this is our back of house inventory, so this will have the information about each product that will be used in our recipes. Recipe Line Item: This is the tricky table, I want to be able link to the ingredients here as well as the quantity needed for the recipe, but I also need to be able to directly include recipes from the recipe table (such as marinara sauce that we make in-house), and that is why I am having trouble figuring out the best way to design this table. Basically, the recipe line item table needs to be able to link to either the ingredients table or the recipe table depending on which line item is needed and I want to know what would be the most effective way to handle that. Thank you so much in advance!

    Read the article

  • mysql compatability error - rake aborted error on rake db:create

    - by user1904563
    I'm a starter in ROR I' m using ruby 1.9.3 and rails 3.2.1 This is what appears on using rake db:create command **>rake db:create rake aborted! Please install the mysql adapter: 'gem install activerecord-mysql-adapter' <can't activate mysql <~> 2.8.1>, already activated mysql-2.9.0-x86-mingw32. Make sur all dependancies are added to Gemfile.>** Have installed mysql gem and copied libmysql.dll file to Ruby193/bin (Phpmyadmin and xampp also works good). Please help me to solve this issue.

    Read the article

  • XPath - get parent node

    - by chris.shi
    //* [ local-name()='component' and namespace-uri()='urn:hl7-org:v3' ] using thispath ,I can get a node like this: <component xmlns="urn:hl7-org:v3"> <structuredBody> <component> <section> <code code="10164-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/> <title>History of Present Illness</title> <text> </text> </section> </component> <component> ...... </component> <component> ...... </component> <structuredBody/> <component/> in order to get the node as below: <component> <section> <code code="10164-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/> <title>History of Present Illness</title> <text> </text> </section> </component> I change the path to : //* [ local-name()='component' and namespace-uri()='urn:hl7-org:v3' and position()=1] but ,how can I get the same result by using [code="10164-2"] as a qualification. ( I do not know how to describe this question ,as a result ,the title of this question is a little simple ,sorry .) thanks

    Read the article

  • Why are difference lists more efficient than regular concatenation?

    - by Craig Innes
    I am currently working my way through the Learn you a haskell book online, and have come to a chapter where the author is explaining that some list concatenations can be ineffiecient: For example ((((a ++ b) ++ c) ++ d) ++ e) ++ f Is supposedly inefficient. The solution the author comes up with is to use 'difference lists' defined as newtype DiffList a = DiffList {getDiffList :: [a] -> [a] } instance Monoid (DiffList a) where mempty = DiffList (\xs -> [] ++ xs) (DiffList f) `mappend` (DiffList g) = DiffList (\xs -> f (g xs)) I am struggling to understand why DiffList is more computationally efficient than a simple concatenation in some cases. Could someone explain to me in simple terms why the above example is so inefficient, and in what way the DiffList solves this problem?

    Read the article

  • Pass dynamic value in URL with CakePHP

    - by Renato Dinhani Conceição
    I have the following method that performs an Ajax request passing some dynamic value obtained from a select input. It works fine, but the dynamic value is passed as parameter in the URL, something like states/listCities/?big_string_of_serialized_parameter . $this->Js->event( 'change', $this->Js->request( array( #url 'controller' => 'states', 'action' => 'listCities'), array( # ajax options that generates the serialized parameter 'update' => '#DealerCityId', 'data' => '$("#DealerStateId").serialize()', 'dataExpression' => true ) ) ); I'm trying to do this in a more friendly URL way, something like states/listCities/2. It's possible in CakePHP to generate a friendly URL like this with dynamic value from a input or is only possible passing the dynamic values as parameters?

    Read the article

  • How to update csv column names with database table header

    - by user1523311
    I am facing this problem some past days and now frustrate because I have to do it. I need to update my CSV file columns name with database table header. My database table fields are different from CSV file. Now the problem is that first I want to update column name of CSV file with database table headers and then import its data with field mapping into database. Please help me I don't know how I can solve this. This is my php code: $file = $_POST['fileName']; $filename = "../files/" . $file; $list = $_POST['str']; $array_imp = implode(',', $list); $array_exp = explode(',', $array_imp); $fp = fopen("../files/" . $file, "w"); $num = count($fp); for ($c = 0; $c < $num; $c++) { if ($fp[c] !== '') { fputcsv($fp, $array_exp); } } fclose($fp);

    Read the article

  • Announcing the ASP.NET and Web Tools 2012.2 Release Candidate

    - by ScottGu
    This week the ASP.NET and Visual Web Developer teams delivered the Release Candidate of the ASP.NET and Web Tools 2012.2 update (formerly ASP.NET Fall 2012 Update BUILD Prerelease). This update extends the existing ASP.NET runtime and adds new web tooling to Visual Studio 2012. Whether you use Web Forms, MVC, Web API, or any other ASP.NET technology, there is something cool in this update for you. You can download and install the RC today: http://www.asp.net/vnext. Great ASP.NET Enhancements This update adds new ASP.NET templates and features, including: New ASP.NET MVC templates. Creating Facebook applications just became easier using the new Facebook Application template. In just a few easy steps you can create a Facebook application that gets data from the logged in user as well as integrates with their friends. A new Single Page Application template allows developers to build interactive client-side web apps using Knockout, jQuery, and ASP.NET Web API. Real-time communication support with ASP.NET SignalR.  This enables you to easily take advantage of the new WebSocket support in .NET 4.5, while also automatically degrading to long-polling and other protocols for older clients.  If you haven’t tried SignalR yet you should – it is awesome. New ASP.NET Web API functionality, including support for OData, integrated tracing, and automatically generating help page documentation for your API. New ASP.NET Friendly URL functionality. This new feature makes it very easy for Web Forms developers to generate cleaner looking URLs (without the .aspx extension). The Friendly URLs feature also makes it easier for developers to add mobile support to their applications with support for mobile .ASPX pages and  supporting switching between desktop and mobile views. It can be used with existing ASP.NET v4.0 applications. Visual Studio 2012 Web publishing enhancements. Web site projects now have the same publish experience as web application projects (including to Windows Azure Web Sites), and you can selectively publish files, see the differences between local and remote files, and update local to remote files or vice versa. Visual Studio 2012 Page Inspector enhancements. JavaScript selection mapping is now supported, and you can CSS updates in real-time. Visual Studio 2012 editor support for Knockout IntelliSense and pasting JSON as a .NET class (which makes it even easier to consume Web APIs from others). Visual Studio 2012 Project Template updates, including the latest versions of jQuery, jQuery UI, jQuery Validation, Modernirz, Knockout and more… How it is delivered You can download and install an integrated setup that contains the above enhancements today from http://www.asp.net/vnext. The new runtime functionality is delivered to ASP.NET via additional NuGet packages. This means that installing this update does not make any changes to the existing ASP.NET binaries, and thus does not cause any compatibility issues with existing projects. New projects will contain the new functionality and existing projects can be updated with the new NuGet packages. Summary Web development is changing, and ASP.NET is rapidly delivering new capabilities to developers that help them take full advantage of new capabilities.  The ASP.NET and Web Tools 2012.2 update installs in minutes without altering the current ASP.NET run time components. For a complete description see the Release Notes. Next week I plan to publish a tutorial showing how to build a cool Facebook application using the new Facebook template. Hope this helps, Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • Loading Entities Dynamically with Entity Framework

    - by Ricardo Peres
    Sometimes we may be faced with the need to load entities dynamically, that is, knowing their Type and the value(s) for the property(ies) representing the primary key. One way to achieve this is by using the following extension methods for ObjectContext (which can be obtained from a DbContext, of course): 1: public static class ObjectContextExtensions 2: { 3: public static Object Load(this ObjectContext ctx, Type type, params Object [] ids) 4: { 5: Object p = null; 6:  7: EntityType ospaceType = ctx.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace).SingleOrDefault(x => x.FullName == type.FullName); 8:  9: List<String> idProperties = ospaceType.KeyMembers.Select(k => k.Name).ToList(); 10:  11: List<EntityKeyMember> members = new List<EntityKeyMember>(); 12:  13: EntitySetBase collection = ctx.MetadataWorkspace.GetEntityContainer(ctx.DefaultContainerName, DataSpace.CSpace).BaseEntitySets.Where(x => x.ElementType.FullName == type.FullName).Single(); 14:  15: for (Int32 i = 0; i < ids.Length; ++i) 16: { 17: members.Add(new EntityKeyMember(idProperties[i], ids[i])); 18: } 19:  20: EntityKey key = new EntityKey(String.Concat(ctx.DefaultContainerName, ".", collection.Name), members); 21:  22: if (ctx.TryGetObjectByKey(key, out p) == true) 23: { 24: return (p); 25: } 26:  27: return (p); 28: } 29:  30: public static T Load<T>(this ObjectContext ctx, params Object[] ids) 31: { 32: return ((T)Load(ctx, typeof(T), ids)); 33: } 34: } This will work with both single-property primary keys or with multiple, but you will have to supply each of the corresponding values in the appropriate order. Hope you find this useful!

    Read the article

  • Binding MediaElement to a ViewModel in a Windows 8 Store App

    - by jdanforth
    If you want to play a video from your video-library in a MediaElement control of a Metro Windows Store App and tried to bind the Url of the video file as a source to the MediaElement control like this, you may have noticed it’s not working as well for you: <MediaElement Source="{Binding Url}" /> I have no idea why it’s not working, but I managed to get it going using  ContentControl instead: <ContentControl Content="{Binding Video}" /> The code behind for this is: protected override void OnNavigatedTo(NavigationEventArgs e) {     _viewModel = new VideoViewModel("video.mp4");     DataContext = _viewModel; } And the VideoViewModel looks like this: public class VideoViewModel {     private readonly MediaElement _video;     private readonly string _filename;       public VideoViewModel(string filename)     {         _filename = filename;         _video = new MediaElement { AutoPlay = true };         //don't load the stream until the control is ready         _video.Loaded += VideoLoaded;     }       public MediaElement Video     {         get { return _video; }     }       private async void VideoLoaded(object sender, RoutedEventArgs e)     {         var file = await KnownFolders.VideosLibrary.GetFileAsync(_filename);         var stream = await file.OpenAsync(FileAccessMode.Read);         _video.SetSource(stream, file.FileType);     } } I had to wait for the MediaElement.Loaded event until I could load and set the video stream.

    Read the article

  • GPO Startup Script can't modify HKU Registry?

    - by pepoluan
    I've been scratching my head with my current problem. You see, I have this Startup Script that I pushed via GPO. Problem is, although the script starts alright (I see the event it created when starting in the event log), it always fails when trying to enumerate and/or modify registry settings under HKU. If I login as administrator and execute the script manually, it works! If I startup a Command Prompt as SYSTEM (using the "at" workaround) and execute the script manually, it also works! If I reboot... the script always fails. Can anyone shed a light on my problem? Additional information: This script injects some registry values for the Local Administrator (i.e., S-1-5-21-etc etc etc-500), so I'm not sure that it's doable via GPP, not to mention that since nearly all the workstations in my domain are still using XP, so no guarantee of GPP support.

    Read the article

  • Syslog permissions

    - by Niels Kristian
    I'm using the $InputFile facility in rsyslog to monitor various log files scattered around my ubuntu 12.04 server. E.g. nginx, unicorn, rails, postgres, cron etc. Now my problem is, that some of these log files are created with -rw-r----- right, so rsyslog doesn't have read rights. Since I install most of the programs using apt-get, and therefore didn't change anything from default. So, in other words, I would like not to modify every singe log file / daemon to have the right permissions, if I instead could give syslog read access to all of them at once. But the question is - can I do that, and is it the "right thing to do"?

    Read the article

  • How to upgrade Nginx?

    - by jwerre
    I'm on Ububtu and I'm trying upgrade Nginx 1.0.5 to the latest version 1.2.6. Here's what I did and what didn't work. $ nginx -v nginx: nginx version: nginx/1.0.5 $ curl -O http://nginx.org/download/nginx-1.2.6.tar.gz $ tar xvzf nginx-1.2.6.tar.gz $ cd nginx-1.2.6/ $ ./configure $ make && sudo make install $ nginx -v nginx: nginx version: nginx/1.0.5 <<< still old version!!! Any ideas would be much appreciated. Thanks.

    Read the article

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