Wednesday, April 20, 2011

WCF windows service issue with MSDTC

I've a .net 3.5 windows service which uses msmq running on 2008 application server.This service communicates with the sql 2005 database on the database server.

Am getting an error mentioned below on calling this service from my aspx page on 2008 web server:

"Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool. The transaction manager has disabled its support for remote/network transactions. (Exception from HRESULT: 0x8004D024)"

I followed this instruction, but no luck.

When I debug the code, above error is thrown at a line in my windows service code where its trying to execute stored procedure using ExecuteNonQuery method.

What am i missing here?

FYI, my web.config on the web server looks like:

<netMsmqBinding>
    <binding name="NetMsmqBinding_IWcfEmailService" closeTimeout="00:01:00"
        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
        deadLetterQueue="System" durable="true" exactlyOnce="true"
        maxReceivedMessageSize="5000000" maxRetryCycles="2"
        receiveErrorHandling="Fault"
        receiveRetryCount="5" retryCycleDelay="00:30:00" timeToLive="1.00:00:00"
        useSourceJournal="false" useMsmqTracing="false" queueTransferProtocol="Native"
        maxBufferPoolSize="524288" useActiveDirectory="false">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="None">
        <transport msmqAuthenticationMode="WindowsDomain"
            msmqEncryptionAlgorithm="RC4Stream"
            msmqProtectionLevel="Sign" msmqSecureHashAlgorithm="Sha1" />
        <message clientCredentialType="Windows" />
      </security>
    </binding>
</netMsmqBinding>
From stackoverflow
  • have you tried enabled network access on the db server as well? There are also several options on the connection you can specify to control how the driver participates in transactions.

  • You need to enable msdtc. See:

    http://stackoverflow.com/questions/7694/how-do-i-enable-mstdc-on-sqlserver

    You must also say to SQL Server that it should allow connections (remote TCP?). That can be done from the SQL Server Surface Area Configuration.

  • I assume you have enabled the DTC for remote access ...

    Administrative Tools –> 
    Component Services –> 
    My Computer properties –>
    MSDTC tab –> 
    Security Configuration tab –>
    Network DTC Access (checked)
    

    If so, here's a handy DTC troubleshooting guide. It's BizTalk centric, but the concepts are the same.

String.Format() split integer value

I'm wondering if it's possible for .Net's String.Format() to split an integer apart into two sub strings. For example I have a number 3234 and I want to format it as 32X34. My integer will always have 4 or 6 digits. Is this possible using String.Format()? If so what format string would work?

P.S. I know there is other ways to do this, but i'm specifically interested to know if String.Format() can handle this.

From stackoverflow
  • No, it can't.

    In fact, it seems that your integers aren't integers. Perhaps they should be stored in a class, with its own ToString() method that will format them this way.

    Samuel : Gah, at least try it once before posting.
    John Saunders : Try what? I've done the ToString override, and it works. I've never done a format string like that below, nor ever seen one.
  • You can specify your own format when calling String.Format

    String.Format("{0:00x00}", 2398) // = "23x93"
    
    James : +1 let me give that shot.
    James : Works like a charm for the four digit numbers. I'll probably end up using a variation of Jeff's solution for the 4 and 6 digit condition but you get the question points for coming up with the hard part.
    Adam Neal : Why did I never try this before...I was doing substring() Thanks! :)
  • James, I'm not sure you've completely specified the problem.

    If your goal is to put the 'x' in the center of the string, Samuel's answer won't work for 6 digit numbers. String.Format("{0:00x00}", 239851) returns "2398x51" instead of "239x851"

    Instead, try:

    String.Format(val<10000 ? "{0:00x00}" : "{0:000x000}", val)
    

    In either case, the method is called Composite Formatting.

    (I'm assuming the numbers will be between 1000 and 999999 inclusive. Even then, numbers between 1000 and 1009 inclusive will report the number after the 'x' with an unnecessary leading '0'. So maybe this approach is valid for values between 1010 and 999999 inclusive.)

    Samuel : That's assuming he wants 123x456 instead of 1234x56.
    John Saunders : And this is why I suggested a class. He may be storing the data in an integer, but it does not have the semantics of an integer.
    James : +1 i'll be using a variation of your solution for the 4 and 6 digit condition.

How can I switch Content Views with an water-effect transition?

In the Photos app, there is a nice water drop effect used for transition. I had seen an app a while ago that used this same water effect transition for it's content views.

Unfortunately, this transition type is not listed in the UIViewAnimationTransition documentation. But since this third party app used it (I don't remember it's name), I guess that there is a way of using it.

Does anyone know?

From stackoverflow
  • It is not part of the published SDK. If you want to sell your app in the app store, you need to implement this yourself.

    Thanks : actually i would it make for free... but i guess that makes no difference ;)
  • I think it's just a hidden CATransition type:

    CATransition *transition = [CATransition animation];
    transition.type = @"rippleEffect";
    transition.duration = 5.0f;
    transition.timingFunction = UIViewAnimationCurveEaseInOut;
    [self.layer addAnimation:transition forKey:@"transitionViewAnimation"];
    

    (Note: I haven't tried this for rippleEffect but I have used suckEffect and spewEffect similarly)

    Thanks : thanks! I tried that, but seems to not work on the simulator. Is that private API stuff?
    rpetrich : The simulator only supports most of the public animation types; the private ones such as suckEffect will show as a fade transition.

Query by month from date field

I have a set of Access d/b's grouped already by year. within a given year, I have a field caleld REPORTDATE which is a standard mm/dd/yyyy field. However, I need to produce queries that return data by the month. For example, I just want to see records for Jan, recs for Feb, Recs for March, etc., so that I can sum them and work wwith thm.

Do I use an expression in the query design view Criteria field?

Thanks in advance.

From stackoverflow
  • You can use format, for example:

    Format([REPORTDATE],"mmm yy")
    

    Or Month:

    SELECT * FROM Table WHERE Month([REPORTDATE]) = 10
    

    An outline of query that may suit, paste this into the SQL view of the query design window, changing table to the name of your table:

    SELECT Format([REPORTDATE],"yyyy mm"), Count([ReportDate])
    FROM Table
    GROUP BY Format([REPORTDATE],"yyyy mm")
    
    Sergej Andrejev : groups by month and this is what you want
    Remou : The first example would be used for Group By (the sum button) and the expression would go on the Field line, instead of REPORTDATE. The second example would be pasted in the SQL view of the query design window, you would have to change Table to the name of your table.
    Remou : Your comment crossed with mine. use the first example, on the field line, it will create the new field you want. It will return Jan 09, Feb 09, but you can change to Format([REPORTDATE],"mm") or Format([REPORTDATE],"m") or Format([REPORTDATE],"yyyy mm") and so on.
    Remou : No. Use the View menu to select SQL View, or choose SQL view from the dropdown list on the toolbar - it will probably be the first item on the far left of the toolbar. SQL view will give you a large blank box.
  • I just want to see records for Jan, recs for Feb, Recs for March, etc., so that I can sum them and work wwith thm.

    You can do all of that in one sql statement:

    select month(reportdate), sum( the column you wish to sum )
    from tablename
    group by month(reportdate);
    

    BUT WAIT THERE'S MORE!

    Further say that there are several salepersons selling stuff, and you wish to show each salesperson's sales by month

    select month(reportdate), saleperson, sum( the column you wish to sum )
    from tablename
    group by month(reportdate), salesperson;
    

    That show the sum per month per saleperson.

    You know the Germans always make good stuff!

    What it you wanted to see the same sums, but rtaher than comparing salespeople against each other in each month, you wanted to compare, for each salesperson, how they did from one month to another?

    Just reverse the order of the group by:

    select month(reportdate), saleperson, sum( the column you wish to sum )
    from tablename
    group by salesperson, month(reportdate);
    

    Tacos, Fettuccini, Linguini, Martini, Bikini, you're gonna love my nuts!

    The power of SQL! As seen on TV! Order now!

    "select month(reportdate), sum( the column you wish to sum )from tablenamegroup by month(reportdate);" THIS IS VERY HELPFUL, THANK YOU. AND YOU ARE HILARIOUS. HOWEVER, can you clarify for me where the heck this code goes?! In the expresison Builder or what? Thank you SO much. – rick (19 mins ago)

    In Access, I think from the graphical Query Builder thing's menu, select edit|SQL, and just type. And never go back to graphical!

    You're a hard-charging forward-thinking entrepreneurially-minded man on the move! This is not your father's Oldsmobile! You wouldn't use an on-screen keyboard to type a document, dragging and dropping letters on the page, would you?! So why do that to build a SQL Query? Get into SQL! AS SEEN ON TV! All the cool kids and hep cats are doin' it! Order NOW!

    tpdi : Great! But I should be that to you. It is powerful, and sum() is only the start of it. And I would appreciate an "accepted answer" from you.
  • I wouldn't do this in the report's recordsource. I'd make the recordsource a regular SELECT statement and use the report's sorting/grouping. If you group on a date field (one that is really date type), you get the choice to GROUP ON:

    Each Value (default) Year Qtr Month Week Day Hour Minute

    I think this is faster than a GROUP BY on a function, but someone who was interested should actually try it.

    Certainly if your SELECT with GROUP BY has no WHERE clause, it's going to be a lot more efficient if you run the report with filtered values.

Transferring Python modules

Basically for this case, I am using the _winreg module in Python v2.6 but the python package I have to use is v2.5. When I try to use:

_winreg.ExpandEnvironmentStrings

it complains about not having this attribute in this module. I have successfully transferred other modules like comtypes from site-packages folder.

But the problem is I don't know which files to copy/replace. Is there a way to do this? Also is site-packages the main places for 3rd party modules?

From stackoverflow
  • It's a compiled C extension, not pure Python, so you generally can't simply copy the DLL/so file across from one installation to another: the Python binary interface changes on 0.1 version number updates (but not 0.0.1 updates). In any case, _winreg seems to be statically build into Python.exe on the current official Windows builds rather than being dropped into the ‘DLLs’ folder.

    _winreg.ExpandEnvironmentStrings is not available pre-2.6, but you could usefully fall back to os.path.expandvars, which does more or less the same thing. (It also supports $VAR variables, which under Windows you might not want, but this may not be a practical problem.) You're right: %-syntax for expandvars under Windows was only introduced in 2.6, how useless. Looks like you'll need the below.

    If the worst comes to the worst it's fairly simple to write by hand:

    import re, os
    
    def expandEnvironmentStrings(s):
        r= re.compile('%([^%]+)%')
        return r.sub(lambda m: os.environ.get(m.group(1), m.group(0)), s)
    

    Though either way there is always Python 2.x's inability to read Unicode envvars to worry about.

    Joan Venge : I tried expandvars, but got %TEMP% on v2.5. I got correct path in v2.6.
    Joan Venge : Thanks your method works great.

ORMs are to RDBMSs as xxx is to OLAP cubes? Does xxx exist?

Is there an ORM-analogue for querying OLAP cubes / data-warehouses? I'm specifically interested in the .NET world, but generally interested in anything ;-)

From stackoverflow
  • ADOMD will let you roll your own. I haven't seen any good libraries that sit on it and provide an easy API for result sets, perhaps due to the nature of Analysis Services and MDX?

    http://msdn.microsoft.com/en-us/library/ms123483.aspx

    I've looked for better, so I'm all ears if anyone has any solutions. Currently for quick development I'm using SQL Server to send MDX queries through a linked server to SSAS, then returning that as stored procedure output from SQL Server, as anyone can then deal with that. Problems I encountered were the lack of debugging, and if the rows are missing it errors, so TRY/CATCH for specific error numbers and a rethrow if not.

  • I've started an open source project, Kona, to wrap the ADOMD.Net lib, and try to bring ADOMD.Net into the 21st Century. You can get it up at http://www.codeplex.com/kona, but it does need some more love and attention.

    The task of converting lambdas to MDX isn't a small one, so I haven't even tried to to that, yet. I've tried to encourage MSFT to write a LINQ to MDX provider, but considering how few .Net developers are actually trying to work with OLAP/SSAS (outside of the SSRS space), I don't think it will be high on anyone's priority list at the moment. But that doesn't mean to stop trying. I've been doing my "BI for the .Net Guy" talk at the local user groups and Code Camps, trying to spread the love.

How to use variable for database name in t-sql

I use the database name in several places in my script and I want to be able to quickly change it, so I'm looking for something like this:

DECLARE @DBNAME VARCHAR(50)
SET @DBNAME = 'TEST'

CREATE DATABASE @DBNAME
GO
ALTER DATABASE @DBNAME SET COMPATIBILITY_LEVEL = 90
GO
ALTER DATABASE @DBNAME SET RECOVERY SIMPLE 
GO

But it doesn't work. So what's the correct way to write this code?

Thanks

From stackoverflow
  • You cannot use a variable in a create table statement. The best thing I can suggest is to write the entire query as a string and exec that.

    Try something like this:

    declare @query varchar(max);
    set @query = 'create database TEST...';
    
    exec @query;
    
  • Unfortunately you can't declare database names with a variable in that format.

    For what you're trying to accomplish, you're going to need to wrap your statements within an EXEC() statement. So you'd have something like:

    SELECT @Sql ='CREATE DATABASE ' + @DBNAME
    

    Then call

    EXEC(@Sql) or sp_executesql(@Sql)
    

    to execute the sql string.

  • Put the entire script into a template string, with {SERVERNAME} placeholders. Then edit the string using:

    SET @SQL_SCRIPT = REPLACE(@TEMPLATE, '{SERVERNAME}', @DBNAME)
    

    and then run it with

    EXECUTE @SQL_SCRIPT
    
    Andrew Hare : +1 Nice use of "replace".

Rails : uninitialized constant error on Active Record destroy

Hello

I am having an issue when trying to destroy an active record instance.

It involves the following AR

class Client < ActiveRecord::Base
    has_many :phone_numbers, :dependent => :destroy
    has_many :email_addresses, :dependent => :destroy
    has_many :user_clients , :dependent => :destroy
    has_many :users, :through => :user_clients 
end

class UserClient  < ActiveRecord::Base
belongs_to :user
belongs_to :client , :dependent => :destroy
has_many :instructions, :dependent => :destroy
end

When performing a destroy on a Client instance I am given the following error

@dead_man = Client.find(params[:id])
@dead_man.destroy => uninitialized constant UserClient::Instruction

I am really not sure where this error is coming from. Any help is greatly appreciated!

From stackoverflow
  • Is this all the code in those models, or are there other callbacks?

    rube_noob : there are no other callbacks
  • It's not finding your Instruction model. Make sure it's in the models directory, appropriately named, extends ActiveRecord::Base, etc.

    Also, you should remove the :dependent => :destroy from the belongs_to :client line in the UserClient model, unless you really want deletion of a user_client to result in deletion of the client. It sounds like it should be the other way around, and that's already set up in the Client model.

App.config - encrypted section error:

I have an application that encrypts a section in the configuration file. In the first time that I try to read the encrypted section from the config file I get an error message: "Unrecognized attribute 'configProtectionProvider'. Note that attribute names are case-sensitive. "

config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
// Get the section in the file.   
ConfigurationSection section = config.GetSection("EncryptedSection");


if (section != null)      
{           
    // Protect the section.
    section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
    section.SectionInformation.ForceSave = true;

    // Save the change.

    config.Save(ConfigurationSaveMode.Modified);  
}  
ConfigurationManager.RefreshSection("EncryptedSection");  
Properties.Settings.Default.Reset();

//This is the part where I read the encrypted section:

ConfigurationManager.RefreshSection("EncryptedSection");
System.Collections.IDictionary HSMMasterKeyConfig = (System.Collections.IDictionary)System.Configuration.ConfigurationManager.GetSection("EncryptedSection");

This only happens in the first time that I try to read the encrypted section. I have noticed that the .config file is getting updated immediately after the first save but from some reason I need to restart the application in order to use the encrypted section.

From stackoverflow
  • Have you read through this...

    http://bytes.com/groups/net/521818-configurationerrorexception-when-reading-protected-config-section

    ... as it appears to be a conversation involving an MSFT support engineer that directly maps to your situation.

  • Try this: http://blog.whconsult.com/2009/04/07/UnrecognizedAttributeConfigProtectionProvider.aspx

  • The best way to do this will be to encrypt the app.config sections during installation only. Add an installer class to your project and override the Install method in the class. In this method you should perform the Encryption. You must call base.Install at the end of your overridden Install method. In the Setup Project goto Custom Actions and locate the Install custom action to be pointed with Your Project output [exe or assembly] which contains the definition of your Installer class implementation. This way it will Encrypt your app.Config sections during an installation straight and you will not face this problem. The application will automatically use DPAPI provider to read/write through sections or settings.

    Hope this helps.

    Thanks.

    Ruchit S.

  • Try running your Exe in seperate Application Domain. Once your application is loaded in the new AppDomain, check if the Sections are encrypted or not. If not then Encrypt the section and trigger the AppDomain to unload and reload with your executable again.

  • For your reference the issue was that the process that was trying to encrypt the config section didn't have admin rights. I added this process to the administrators group and that solved it.

Asp.Net binding SQL data to a repeater?

I am trying to bind data from SQL to a repeater control. I have tried what I usually do for a Gridview and it doesn't work. I would like to see an example whether it be using an SQLAdapter or using ExecuteReader from a command. Thank you!

string sql = "SELECT [WallPost], [DatePosted] FROM [WallTable] WHERE [UserId] = '"
 + Request["friend"] + "'";

string strCon =      
System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;

SqlConnection conn = new SqlConnection(strCon);

SqlDataAdapter daUserProfile = new SqlDataAdapter(sql, conn);

dsSocialSite.UserProfileDataTable tbUserProfile = 
    new dsSocialSite.UserProfileDataTable();

daUserProfile.Fill(tbUserProfile);

rpWall2.DataSource = tbUserProfile; //rpWall2 = repeater control

rpWall2.DataBind();
From stackoverflow
  • Using an example I had knocked up the other day

    <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" 
    AutoEventWireup="true"CodeFile="Default.aspx.cs" Inherits="Default2"
    Title="Untitled      Page" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
    Runat="Server">
    <div id="Questions" align="center" style="background-color: #C0C0C0">
        <asp:Repeater ID="QuestionsRepeater" runat="server" 
             DataSourceID="SqlDataSourceQuestions">
        <ItemTemplate>
        <div align="left" style="text-indent: 15px">
            <asp:Label ID="Label1" 
             runat="server" Text= '<%# Eval("QCategory") %>' 
             Font-Bold="True" Font-Size="Medium"></asp:Label>
        </div>
    
            <br />
            <asp:RadioButtonList ID="RadioButtonList1" runat="server" 
             DataSourceID="SqlDataSourceRatings" DataTextField="RatingsCategory" 
             DataValueField="RatingsCategory"  RepeatDirection="Horizontal" >
            </asp:RadioButtonList>
    
        </ItemTemplate>
    </asp:Repeater>
    
    <asp:SqlDataSource ID="SqlDataSourceQuestions" runat="server" 
        ConnectionString="<%$ ConnectionStrings:sandboxConnectionString %>" 
        SelectCommand="SELECT [QCategory] FROM [QuestionsCategory]">
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="SqlDataSourceRatings" runat="server" 
    ConnectionString="<%$ ConnectionStrings:sandboxConnectionString %>" 
    SelectCommand="SELECT [RatingsCategory], [RatingsId] FROM [Ratings]">
    

    : Thank you, I am actually looking to do it using the code behind the page. I appreciate it!
    : Ok I actually tried it this way and when I test the query, it shows the info I want. It looks exactly like your code because I did it in design view. When I go to view the page, nothing shows up???
    : Nevermind that worked...I forgot to add the Template.
  • Doing it on the html (as in John Nolans answer) side is easier with the repeater since it uses templates.

    If you want to do it in code behind, create a class that implements ITemplate then place it like so:

    myRepeater.ItemTemplate = new MyTemplateClass();
    

ASP.NET MVC. No idea how to use Url.action to pass an object to the controller

I am new to asp.net MVC. I was able to create my view and display the data (Gridview). Additionally, I was able to create a hyperlink (using Url.Action) passing string and int types. However, I want to create a hyperlink that it is referencing a more complex type. The class associated with my view has a reference to a List. What I want is to create an additional ActionResult in my controller that gets as a parameter List (See below)

public ActionResult ViewItems(List<Items> c)
{            
    return View(c);
}

My idea is when is to be able to pass that List to the controller and then the controller will call the corresponding view. I tried (See below) but I just get blank.

<asp:HyperLink ID="LinkContractID" runat="server" NavigateUrl='<%#Url.Action("ViewItems", new {c = **((Contract)Container.DataItem).ContractItems.ToList<Items>(**)}) %>'
Text='<%# Eval("ContractId") %>'></asp:HyperLink>
From stackoverflow
  • If you are looking for a grid, this tutorial shows how to create a grid with MVC.

  • With MVC, you shouldn't use Gridview and asp: controls. If you want to generate a link, just use <%=Html.ActionLink(...) %> with the necessary parameters.

  • Like in the previous answer, you don't use asp controls. There are pros and cons with Html.ActionLink however, it isn't so good if you want to put a link around an image for instance. In this case the syntax would be

    <a href="<%= Url.Action(
       "ShowListPage", "MyController", new { modelId = 101 }) %>">
       <img src="img.gif" />
    </a>
    

    Also with your action in the controller, you would ideally be looking to have this go and get the model to pass to a view strongly typed to this model. So you have a model object with a constructor taking an id, for instance

    public MyModel(int modelId)
    {
       this.TheListThatHoldsTheGridData = MyDataLayerProc(modelId);
    }
    

    This way you can have your action in the MyController controller, return the view ShowListPage (associated with a MyModel instance) like so

    public ActionResult ShowListPage(int modelId)
    {
       return View(new MyModel(modelId));
    }
    

    Hope this helps,

    Mark

Python __str__ and lists

Hello

In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:

"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"

Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:

print 'my list is %s'%(list)

it looks something like this:

[<__main__.cell instance at 0x2a955e95f0>, <__main__.cell instance at 0x2a955e9638>, <__main__.cell instance at 0x2a955e9680>]

how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?

From stackoverflow
  • Calling string on a python list calls the __repr__ method on each element inside. For some items, __str__ and __repr__ are the same. If you want that behavior, do:

    def __str__(self):
        ...
    def __repr__(self):
        return self.__str__()
    
  • You can use a list comprehension to generate a new list with each item str()'d automatically:

    print([str(item) for item in mylist])
    
  • Two easy things you can do, use the map function or use a comprehension.

    But that gets you a list of strings, not a string. So you also have to join the strings together.

    s= ",".join( map( str, myList ) )
    

    or

    s= ",".join( [ str(element) for element in myList ] )
    

    Then you can print this composite string object.

    print 'my list is %s'%( s )
    
  • Something like this?

    a = [1, 2 ,3]
    [str(x) for x in a]
    # ['1', '2', '3']
    
  • Depending on what you want to use that output for, perhaps __repr__ might be more appropriate:

    import unittest
    
    class A(object):
        def __init__(self, val):
            self.val = val
    
        def __repr__(self):
            return repr(self.val)
    
    class Test(unittest.TestCase):
        def testMain(self):
            l = [A('a'), A('b')]
            self.assertEqual(repr(l), "['a', 'b']")
    
    if __name__ == '__main__':
        unittest.main()
    
  • I agree with the previous answer about using list comprehensions to do this, but you could certainly hide that behind a function, if that's what floats your boat.

    def is_list(value):
        if type(value) in (list, tuple): return True
        return False
    
    def list_str(value):
        if not is_list(value): return str(value)
        return [list_str(v) for v in value]
    

    Just for fun, I made list_str() recursively str() everything contained in the list.

MDX Calculating Time Between Events

I have a Cube which draws its data from 4 fact/dim tables.

  1. FactCaseEvents (EventID,CaseID,TimeID)
  2. DimEvents (EventID, EventName)
  3. DimCases (CaseID,StateID,ClientID)
  4. DimTime (TimeID,FullDate)

Events would be: CaseReceived,CaseOpened,CaseClientContacted,CaseClosed

DimTime holds an entry for every hour.

I would like to write an MDX statement that will get me 2 columns: "CaseRecievedToCaseOpenedOver5" and "CaseClientContactedToCaseClosedOver5"

CaseRecievedToCaseOpenedOver5 would hold the number of cases that had a time difference over 5 hours for the time between CaseReceived and CaseOpened.

I'm guessing that "CaseRecievedToCaseOpenedOver5" and "CaseClientContactedToCaseClosedOver5" would be calculated members, but I need some help figuring out how to create them.

Thanks in advance.

From stackoverflow
  • This looks like a good place to use an accumulating snapshot type fact table and calculate the time it takes to move from one stage of the pipeline to the next in the ETL process.

    madcolor : thanks for the comment..I'll look into that.
  • Query for AdventureWorks (DateDiff works in MDX):

    WITH 
    MEMBER Measures.NumDays AS 
    'iif(ISEMPTY(([Delivery Date].[Date].CurrentMember
    ,[Ship Date].[Date].CurrentMember
    ,Measures.[Order Count]))
    ,null
    , Datediff("d",[Ship Date].[Date].CurrentMember.Name
    ,[Delivery Date].[Date].CurrentMember.Name))'
    SELECT
    NON EMPTY {[Ship Date].[Date].&[63]
    :[Ship Date].[Date].&[92]} ON COLUMNS,
    NON EMPTY {[Delivery Date].[Date].&[63]
    :[Delivery Date].[Date].&[92]} 
    * {[Measures].[NumDays]
    , [Measures].[Order Count]} ON ROWS
    FROM [Adventure Works]
    

    Taken from: http://www.mombu.com/microsoft/sql-server-olap/t-can-i-have-datediff-in-mdx-265763.html

    If you'll be using this member a lot, create it as a calculated member in the cube, on the Calculations tab if I remember right.

    madcolor : Killer.. thanks.

PHP - Maximum Total Upload Size?

I have a php web page with 15 fields. The user will use it to upload images. I tested this by uploading 15 jpg images, each about 2 M, without any problems. On the day I launch, I will be moving this web page to another Linux shared hosting environment (still not sure which). Are there some web hosting environments that limit the size of total uploads in one http request?

From stackoverflow
  • This would be unusual, but of course, check with whatever hosting company you choose. If there were a limit, it certainly would be higher than 30 MB.

    Benson : The default limit on my linux machine was 2 MB.
    John Rasch : Well yeah, but when you purchase hosting they're going to increase that, and if they don't you can ask them to.
  • the php.ini directive "post_max_size" should limit how much data you can send in a single POST. if you post 15 images in one post I'm pretty sure that is still considered one POST. So it might be good to check this value before going live.

  • It's a setting in php.ini. You can look in the output of php info for the field labeled "upload_max_filesize". To get a php info page, create a php file with the following code:

    <?php phpinfo(); ?>
    

    This post at php.net gives you sample code to get that information, and the rest of the page is a treasure trove of php configuration options.

  • Yes. There are (as far as I can remember) three or so configuration settings which will affect upload size restrictions:

    • upload_max_filesize, which sets an upper limit on the size of uploaded files
    • max_post_size, which limits the total size of posted data, including file data
    • max_input_time, which restricts the length of time the script is allowed to process input data, including posted values

    upload_max_filesize is a limit on each individual file; however, max_post_size is an upper limit on the entire request, which includes all the uploaded files.

    Different hosting environments will have these values set differently, which may affect your abilities upon deployment.

    sjobe : An Apache restart helps after you've made all these changes but nothing happens
  • There are bunch of PHP settings limiting the upload process:

    • file_uploads
    • upload_max_filesize
    • max_input_time
    • memory_limit
    • max_execution_time
    • post_max_size

    I'd suggest reading this page: http://www.radinks.com/upload/config.php

    While it's true many of these don't limit upload size, they do put a cap on the upload process - e.g. if memory limit is too low, then you'll have problems uploading big files that need to stay in memory for a little period of time.

    Gumbo : `file_uploads`, `memory_limit` and `max_execution_time` do not limit the maximum total upload size.
  • The upload limits are set through php ini. You can try get them like so:

    $post_max_size = ini_get('post_max_size');
    $upload_max_filesize = ini_get('upload_max_filesize');
    

SVN Remove File from Repository without deleting local copy.

How can I "delete" a file which is already in the SVN repository without deleting it from my file system?

Tortoise or Command Line instructions welcome.

Thank you.

From stackoverflow
    1. Copy the file to some other location outside the repository.
    2. SVN Delete the file.
    3. Commit
    4. Copy the files back and make sure to ignore them on future commits.

    It would work but I'm hoping for something nicer.

    phihag : As this is obviously not an answer you are looking for, why not edit the question to include it?
  • In Tortoise, use the Repo-browser.

    crashmstr : but that will delete the local file on an update, which is not the desired outcome in this case.
  • svn delete --keep-local the_file
    
    barfoon : I am getting a "svn: invalid option: --keep-local" - Is it because I am on 1.4.6?
    phihag : @barfoon: Yes, --keep-local is only available in svn 1.5.0+. I'm afraid you have to manually copy the file beforehand or check it out using svn cat afterwards.
  • In Tortoise, you can also Shift+Right-click to get a menu that includes "Delete (keep local)".

  • Deleting files and folders

    If you want to delete an item from the repository, but keep it locally as an unversioned file/folder, use Extended Context Menu → Delete (keep local). You have to hold the Shift key while right clicking on the item in the explorer list pane (right pane) in order to see this in the extended context menu.

  • Delete the file from the remote repository:

    svn delete http://svn.yourdomain.com/path/to/file.ext
    
    crashmstr : but that will delete the local file on an update, which is not the desired outcome in this case.
  • Rename your file, commit the changes including the "deleted" file,
    don't include the new (renamed) file.
    Rename your file back.

  • It's retarded that I need reputation to comment but not to provide an answer, so I'm writing my "comment" to the second best answer from Philhag. It has 10 ups, and is completely incorrect. There is no --keep-local option for svn delete. Check any language definition or the redbook. It doesn't exist (at least in the standard implementation).

    If you're using the cmd line, MrGrieves and Avram's response is the correct one. I would give them "ups" but again, Stackoverflow doesn't allow me to with my current rep.

    Ben Blank : That option was added in svn 1.5 — http://svnbook.red-bean.com/en/1.5/svn.ref.svn.c.delete.html#id531291
  • I'm running svn, version 1.6.2 (r37639) this version does support the --keep-local flag (linux cli)

  • Rename your file, commit the changes including the "deleted" file, don't include the new (renamed) file. Rename your file back.

    that works, but the icons still indicate they are in the repository. it seems, sometimes i'm lucky using tortoise's clean up command to also clean up the icons. anybody has a different idea?

What are the best C# .NET books?

What are your top 3 all-time best C# .NET books? And why?

They could be for specific areas of .NET or be more general books.

From stackoverflow
  • I really like

    • CLR via C# by Jeffrey Richter because of all the details about how not only C# but also the CLR works. 3rd edition adds a lot of useful info on threading and the new parallel extensions.
    • Professional .NET 2.0 Framework by Joe Duffy is very similar to Richters book, so I like it for the same reasons. Unfortunately it is somewhat dated now.
    • C# in Depth by Jon Skeet is an excellent treatment of all the stuff that the two others do not cover.
    • The C# language specification (get the book for the annotations). A must read.

    To name another good book: Essential C# 4.0 by Mark Michaelis. Very thorough. (EDIT updated to new edition)

    And C# 4.0 in a Nutshell. Excellent reference. (EDIT updated to new edition)

    Alex Baranosky : Thank you. That is a pretty comprehensive bunch of books I haven't looked at too deeply yet.
    David Basarab : Any book by Jon Skeet is worth its weight in gold.
    Dave Markle : IMO if you haven't read CLR via C# cover to cover, and understood it, you probably aren't an expert C# programmer. +1.
    Jon Skeet : @Longhorn213: Fortunately C# in Depth is quite light :)
    Alex Baranosky : @Jon Skeet, so at about 1.5 lbs and about $8000 per pound for gold, your book should cost me a mere $12000, roughly.
    smwikipedia : @Jon Skeet, Great book. The best way to know something is to know its evolution, you paved the way.
    Jon Skeet : @smwikipedia: You're very kind. I'm definitely pleased with the book, imperfect though it obviously is. I just want to get the second edition out of the door now...
  • I like Rocky Lhotka's Expert C# 2008 Business Objects. It's a good treatment on developing and using a business framework.

    1. HEAD FIRST C#

      this is a really good book for beginners with an alternative learning approach! :)

    2. Programing C# 3.0

    thats i think a real reference for beginners as well as for advanced programmers!

  • C# in Depth And

    The C# programming language

  • The books already posted are excellent. However, I think C# 3.0 Pocket Reference by O'Reilly is also valuable for quick reference and my carry anywhere book.

  • I really like C# in a Nutshell - O'Reily

  • I'd concur with the recommendations for C# 3.0 in a Nutshell and Accelerated C# 2008, and also add Essential C# 3.0 by Mark Michaelis. (No time to look up links right now, I'm afraid.)

    I have reviews of various books, mostly C#-based, on my blog in the Book Reviews tag. Obviously I'm not entirely unbiased on this matter, but what matters to me most is accuracy. That was my biggest gripe with both Head First C# and Programming C# 3.0. I know that most of the errors are now fixed in Head First C#, so if you get a recent printing you should be okay. It's not my preferred style of book, but that's a matter of personal preference. I don't know whether there have been any more printings of Programming C# 3.0.

    If you want detailed CLR information, CLR via C# is truly wonderful.

  • CLR via C#,

    C# in Depth - thanks Jon!,

    Programming .Net components by Juval Lowy.

  • Perhaps not so obvious but I think that Joshua Bloch's Effective Java 2nd edition is an outstanding book for C# developers. While some of it may not be directly relevant to C#, most of it is very applicable. It's well worth the read.

    Alex Baranosky : nice out of the box idea.
    Jon Skeet : +1: It's a wonderful, wonderful book. It's also interesting to see some of the twists and turns required in Java which aren't a problem in C#.
    Alex Baranosky : I just read it. Thanks for the suggestion.
    Jacek S : +1: Great book. It will tech you how to design a good API (not only in Java).
    Tristan Havelick : Jon - I'm wondering if you've looked at Wagner's Effective C# books, and if you believe they are a reasonable corollary to Bloch's or if one should just consult the source directly.
  • Not as indispensible as Scott Meyer's original series for C++, but Effective C# is still a worthy read once you have mastered the basics.

    There is also a More Effective C# too, now, but I haven't read that to be able to recommend it.

    I think beyond those, and more advanced or specialist works like Ritcher's CLR book (already mentioned) the best place to keep current are the various blogs.

    • Programming C# By Jesse Liberty (A good book I used to learn, and still refer to several years on for a refresh on certain topics)
    • CLR Via C# By Jeffrey Richter (Good book for understanding how the lower level internals work)
    • C# Cookbook By Jay Hilyard and Stephen Teilhet (Handy for finding a quick solution in the midst of a project)
    • Effective C#: 50 Specific Ways to Improve Your C# By Bill Wagner (Good read if you've been programming for a while)
  • The C# Programming Language by Anders Hejlsberg

  • Check out my list of good recently published books related to .NET development:

    http://www.riaguy.com/books/

  • Richter: "CLR via C#"

    Troelson: "Pro C# 2008 and the .NET 3.5 Platform"

    Albahari & Albahari: "C# 3.0 in a Nutshell"

    Hejlsberg, Torgersen, Wiltamuth, & Golde: "The C# Programming Language, 3rd Ed."

    Robbins: "Debugging .NET 2.0 Applications"

    Lowy: "Programming WCF Services, 2nd Ed."

    No self-respecting C# programmer can pass over Richter. This will give you a profound understanding of .NET at the "systems" level. Foundational.

    Albahari & Albahari is an absolutely terrific and complete discussion of C# along with basic FCL facilities like networking, collections, Etc. Could serve as a good intro for experienced programmers but will also be great for experienced C# programmers. No coverage of extended FCL classes though.

    Troelson is a standard introductory text and very good. It does not cover things in the Nutshell book in nearly the same depth but does provide much information on the broader FCL libraries, how to create and develop various application types, etc.

    Hehlsberg et. al. is a pretty good reference. Mostly an annotated version of the standard. Not required but good when you really need to know how something is defined in the standard.

    Robbins has published the essential Windows debugging books for years. This one for .NET is just as essential.

    Lowy's book is obviously more specialized than the others, but deserves mention as one of the outstanding technical books available. If you want to do WCF you must have this.

  • Effective C# - Good summary of best practices dos and don'ts

    More Effective C# - More dos and don'ts but updated for 3.5 covers multi-threading and linq

    Pro C# and the .Net 3.5 Platform - A look at every part of the framework. Also it's a nice looking hardcover book.

    I'm assuming that an introduction to C# book isn't required.

  • alt text

    LINQ In Action is a good reference for LINQ.

  • For C# language fondamentals Programming C# 3.0 it also covers some advanced topics (threading , P/invoke ...)

    To learn more advanced stuff have a look at CLR via C# ( i think anybody who uses c# should read this book!)

  • I learnt from "Pro C# 2008 and the .NET 3.5 Platform" and I definately recommend it! Though I'm sure theres a newer version coming out shortly.

  • I quite like:

How would you go about reverting a single file to previous commit state using git?

I wonder why isn't it implemented in the GUI? I know git has a content approach vs. single file approach but sometimes single file reverting is crucial.

For instance an .png graphics file from a few commits before is needed.

Probably I need to do a checkout but I'm still not sure as the concepts sometimes escape me.

From stackoverflow
  • If you know how many commits back you need to go, you can use:

    git checkout master~5 image.png
    

    This assumes that you're on the master branch, and the version you want is 5 commits back.

    hallidave : You can use HEAD~5 rather than master~5 if you're not on the master branch.
    dylanfm : Am I right to think that HEAD^ or master^ goes back just 1 commit?
    Ron DeVera : @dylanfm, that's right.
  • To expand on Ron DeVera's post, where he mentions master~5, you can use any reference to a git commit, including the SHA-1 if that's most convenient. The point is that the command looks like this:

    git checkout [commit-ref] [filename]

    keepyourliberty : Thanks that's useful especially if one doesn't want look for branch names or count how many commits etc.

CeRapiInit or CeRapiInitEx?

CeRapiInit() does not return until a device is connected and initialization is complete (synchronous). CeRapiInitEx() does, but requires a callback event handler (asynchronous). All I want is a "connecting to device" dialog with a cancel button. Which is the better approach? Any code sample out there?

From stackoverflow

UIDatePicker and NSDate

I have an NSDate that I get from a UIDatepicker.

IBOutlet UIDatePicker *dueDate;

NSDate *selectedDate = [dueDate date];

how do I retrieve the month from dueDate in the form of an int? (1 for Jan, 2 for Feb, etc)

From stackoverflow