Howto open ("/dev/urandom") on Windows0 Reacties

Just copy-paste2 might save you some time. rand_s is pretty safe on Windows since it uses RtlGenRandom(), but you’ll have to define _CRT_RAND_S first before

Assuming that the cpp somewhere in the class has: m_fd = open("/dev/urandom", O_RDONLY);

Original code: (thanks jacketzhong)

sds CRedLock::GetUniqueLockId()

{

unsigned char buffer[20];

if (_read(m_fd, buffer, sizeof(buffer)) == sizeof(buffer)) {

//获取20byte的随机数据

sds s; s = sdsempty();

for (int i = 0; i < 20; i++)

{

s = sdscatprintf(s, "%02X", bufferIdea); } return s;

}

else

{

//读取失败 printf("Error: GetUniqueLockId %d\n", __LINE__); }

return NULL;

}

Windows CPP compatible:

note: rand_s is not an ANSI standard.

sds CRedLock::GetUniqueLockId()
{
    //获取20byte的随机数据
    auto retVal = sdsempty();
    auto max = 20 / sizeof(unsigned int);
    for (int i = 0; i < max; i++)
    {
        unsigned int number;
        if (rand_s(&number) == 0)
        {           
            retVal = sdscatprintf(retVal, "%08X", number);           
        }
    }
    return retVal;
}

Give your C# class Initializer support0 Reacties

Would you like a to boost your class which hosts a collection, and utilize a cool C# language feature, which is collection initializer support?

For instance var myList = new List() {1,3,4} where {1,3,4} is the initializer.

The basic idea is to implement IEnumerable, and IEnumerator and the class must have an ‘Add’ method with the correct signature.

I made the class generic so you can initialize any array (ok, not for structs and simple types, but you modify a few things and that works too)

// our sample class for iteration feeding

public class Address
   {
       public string Street { get; set; }
       public string StreetNumber { get; set; }
       public string ZipCode { get; set; }
       public string City { get; set; }
   }
   public static class Program
   {
       static void Main()
       {
           var t = new ClassWithInitializerSupport

{
               new Address()
               {
                   Street = "Mainstr.",
                   StreetNumber = "1",
                   City ="London"
               },
              new Address()
               {
                   Street = "De Dam",
                   StreetNumber = "1",
                   City ="Amsterdam"
               },
               new Address()
               {
                   Street = "Mangostreet",
                   StreetNumber = "123",
                   City ="New York"
               }
           };
           foreach(var a in t)
           {
               Console.WriteLine("Street {0}, City {1}", a.Street, a.City);
           }

}

public class ClassWithInitializerSupport : IEnumerable, IEnumerator where T : class
   {
       public ClassWithInitializerSupport()
       {
           arr = (T[])Array.CreateInstance(typeof(T), 0);
           pos = -1;
       }
       private T[] arr;
       private int pos;
       public T Current => arr[pos];

       object IEnumerator.Current => arr[pos];

       public void Dispose()
       {

       }

       public IEnumerator GetEnumerator()
       {
           return this;
       }
       public void Add(T v)
       {
           var p = arr.Length;
           Array.Resize(ref arr, p + 1);
           arr[p] = v;
       }
       public bool MoveNext()
       {
           if (pos + 1 < arr.Length)
           {
               pos++;
               return true;
           }
           return false;
       }

       public void Reset()
       {
           pos = -1;
       }

       IEnumerator IEnumerable.GetEnumerator()
       {
           return this;
       }
   }

Howto: Azure DocumentDB update/delete objects, without SelfReference0 Reacties

Inherit Microsoft.Azure.Documents.Resource? No

We can be short, just don’t. If you do, your library gets bloated and you need to add references to documentdb to ‘cross-reffed’ libraries as well, because of the ‘Resource’ dependency.

Use a POC based ‘base object’? Yes

If you implement DocumentDB for the first time, you’ll quickly find that documentation and old samples, suggest you, to use the Build in Microsoft.Azure.Documents.Resource base object properties, that DocumentDB supports.

It’s quite simple, don’t use them. There is an improved syntax, like using mongodb, which enables you to define your own id and such.

say, this one

public class BaseObject
    {
        public BaseObject()
        {
            UpdateTimeStamp();
        }
             public void UpdateTimeStamp()
        {
            this.timestamp = DateTime.UtcNow;

        }
 
        [ModelIgnore]
        public virtual int? document_type { get; set; }

        [JsonProperty("id", Required = Required.DisallowNull)]
           public Guid id { get; set; }


        [JsonProperty("timestamp", Required = Required.DisallowNull)]
        public DateTime timestamp { get;  set; }
        ///


        /// warning, do not SET this is a calculated field
        ///

        [JsonProperty("name", Required = Required.DisallowNull)]
        public string name { get; set; }

}

 

Now, your DocumentDB Context class (or whatever you named it) could have a method like this

 

public async Task DeleteItemsAsync(BaseObject item)
        {
                      var collection = MetaUtil.CollectionId(item.GetType());
            
            //calculate the URL ourselves
            // this differs from SelfLink but seems to work!
          
var docuId = UriFactory.CreateDocumentUri(DatabaseId, collection, item.id.ToString());
            try
            {
     
                var response = await _client.DeleteDocumentAsync(docuId);

                   return response.StatusCode == HttpStatusCode.NoContent;
            }
            catch (Exception ex)
            {
                Trace.TraceError("DeleteItem failed {0}", ex);
                return false;
            }
        }

 

 

As you can use, there is a UriFactory class, that contains a lot of static uri creators, for any object type, that DocumentDB supports.

B.t.w. I like DocumentDB. After finding out about https://azure.microsoft.com/en-us/blog/azure-documentdb-bids-fond-farewell-to-self-links/, I quickly could ‘unbloat’ the library :)

SiteMaps made easy0 Reacties

 

If you’re a site admin or asp.net developer for an internet site, you certainly need to look into sitemaps, if you want to perform SEO.

It’s not necessary to  simply crawl your own site and then to give every page a priority, but consider this for a forum or other pages which are irregularly or often updated. If you don’t want to have crawlers do unneeded roundtrips, implement a sitemap.

‘robots.txt’ should contain a reference to your map eg. Sitemap: http://www.myfantasticsite.com/sitemap.xml

Ideas of this class, written using C#, can be found anywhere on the net. However, as some might know me, I like it to be finished and neat and a self-supporting class ready for usage (e.g. it must not be written to a string to add or remove wished attributes that the serializer could not handle).

The following things are solved. 
Since  ‘changefreq’ and ‘lastmod’ and ‘priority’ are optional values, you don’t want the XmlSerializer to create empty tags!
This is done by adding a DefaultValue attribute. It will cause XmlSerializer to check the current value against the default value. If they are equal, it is considered to be an empty non existing tag. Remember, that the defaultvalues need to be out of the range of possible values! Therefore, EnumChangeFreq contains an extra member ‘notused’
Remember, the Xml.Serialization name space, offers the tools to get it done without converting your loading your XML in to some XmlDocument class.

You can use the class as follows.
UrlSet retVal = new UrlSet();

retVal.AddUrl(new Url() { LastModifiedDateTime = DateTime.Now.ToUniversalTime(), Loc = “http://www.myfantasticsite.com/blah.aspx”) });

Retrieve the XML sitemap string.
string xml = null;
using (var io = (MemoryStream)retVal.ToStream())
{
                xml =  new UTF8Encoding().GetString(io.ToArray());
}

or, to write it directly to an output stream

using (var io = (MemoryStream)retVal.ToStream())
{

//todo: Deal with Response.Cache, etag and last modified to avoid unnecessary round trips.
Response.ContentType = “text/xml”;
Response.CharSet = “utf-8”;
Response.BinaryWrite(retVal.ToArray());

}

using System;
using System.Xml;
using System.Xml.Serialization;
using System.ComponentModel;
using System.IO;

namespace adccure
{

    public enum EnumChangeFreq
    {
        notset,
        always,
        hourly,
        daily,
        weekly,
        monthly,
        yearly,
        never
    }

[

[XmlRoot(ElementName = "urlset", Namespace = SCHEMA_SITEMAP)]
public sealed class UrlSet
{
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces xmlns;
    private const string XSI_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance";
    private const string SCHEMA_SITEMAP = "http://www.sitemaps.org/schemas/sitemap/0.9";

    private Url[] _url;

    public UrlSet()
    {
        _url = new Url[0];
        xmlns = new XmlSerializerNamespaces();
        xmlns.Add("xsi", XSI_NAMESPACE);
        SchemaLocation = SCHEMA_SITEMAP + " " + "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd";

    }
    [XmlAttribute(AttributeName = "schemaLocation", Namespace = XSI_NAMESPACE)]
    public string SchemaLocation;

    public void AddUrl(Url url)
    {
        int l = _url.Length + 1;
        Array.Resize(ref _url, l);
        _url[l - 1] = url;
    }

    [XmlElement(ElementName = "url")]
    public Url[] url
    {
        get { return _url; }
        set { _url = value; } //bogus
    }
    ///


    /// serializes the UrlSet to a sitemap.xsd conform string ready for saving to disk.
    ///

    /// a Stream object
    public Stream ToStream()
    {
        XmlSerializer xmlser = new XmlSerializer(GetType());
        var io = new MemoryStream();
        xmlser.Serialize(new StreamWriter(io, Encoding.UTF8), this);
        io.Position = 0;
        return io;
    }
}

    public sealed class Url
    {
        private string _loc;
        private DateTime _lastmod;
        private float _priority;
        private EnumChangeFreq _changefreq;

        public Url()
        {
            //setting defaults
            _changefreq = EnumChangeFreq.notset;
            _priority = 0.0F;
            _lastmod = DateTime.MinValue;
        }

        [XmlElement(ElementName = "loc")]
        public string Loc
        {
            get
            {
                return _loc;
            }

            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException();
                }
                if (value.Length < 12 || value.Length > 2048)
                {
                    throw new ArgumentException("loc must be between 12 and 2048 in length");
                }
                _loc = value;
            }
        }
        [XmlElement(ElementName = "lastmod"), DefaultValue(typeof(DateTime), "1-1-0001")]
        public DateTime LastModifiedDateTime
        {
            get
            {
                return _lastmod;
            }

            set
            {
                _lastmod = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second, value.Kind);

            }
        }
        [XmlElement(ElementName = "changefreq")]
        [DefaultValue(EnumChangeFreq.notset)]
        public EnumChangeFreq ChangeFreq
        {
            get
            {
                return _changefreq;
            }

            set
            {
                _changefreq = value;
            }
        }
        [XmlElement(ElementName = "priority")]
        [DefaultValue(0.0F)]
        public float Priority
        {
            get
            {
                return _priority;
            }

            set
            {
                if (value < 0 || value > 1.0)
                {
                    throw new ArgumentException("Must be between 0 and 1");
                }
                _priority = value;
            }
        }
    }
}

Tags van Technorati: ,,

Performance and the future of LINQ expressions0 Reacties

I was wondering if writing well known C# (or VB.NET if you wish) code flow statements, such as for .. and foreach etc. are faster or slower compared to a generic expression.

The results are refreshing  Big Smile. At least using this simple array iteration. Array Iterations on millions of elements, of course, are not the the real life CPU eaters for an average ASP.NET website (eg), but consider this code.

There are three loops, doing the same.  (n.b.: I run a dual core i7200 CPU machine on Vista x64)

int ctr = 0;

var values = new string[1000000].

        Select(p => p = (ctr++).

        ToString()).

        ToArray();

List<int> intList;

intList = values.Select(p => int.Parse(p)).ToList();

int[] test1, test2, test3;

 // loop 10 times and calculate the average

test1 = new int[10];

test2 = new int[10];

test3 = new int[10];

for (int zz = 0; zz < 10; zz++)

{

    // our millisecond counter

    // it's ok to run this test several times to get an average score

    int start = Environment.TickCount;

    // convert the numeric array back to an int array

    intList = values.Select(p => int.Parse(p)).ToList();

    test1[zz] = Environment.TickCount - start;

    //now do the same but using a foreach iteration

    start = Environment.TickCount;

    intList = new List<int>();

    foreach (var p in values)

    {

        intList.Add(int.Parse(p));

    }

    test2[zz] = Environment.TickCount - start;

   //do it a last time, but with a for{} iteration

    // theoretically a this should save us an enumerator.

    start = Environment.TickCount;

    intList = new List<int>();

    int z = values.Length; 

    for (int x = 0; x < z; x++)

    {

        intList.Add(int.Parse(values[x]));

    }

    test3[zz] = Environment.TickCount - start;

    Console.WriteLine("{0}, {1}, {2}", test1[zz], test2[zz], test3[zz]);

   

}

Console.WriteLine("{0}, {1}, {2}", test1.Average(), test2.Average(), test3.Average());

Console.ReadKey();

To test this, run this code in release mode (plus Ctrl-F5, in Visual Studio).

x64 CPU platform results:
Test 1) 175ms
Test 2) 154 ms
Test 3) 155 ms

x86 CPU platform results:
Test 1) 198 ms
Test 2) 161 ms
Test 3) 169 ms

Test 1 uses an generic expression to 'cast'  a numeric string array to a List of type Int32.
Cute line, isn't it?
But unfortunately, as has been said, the LINQ expression, still is a bit slower than the non-linq versions.

How much slower when we deal with integer math and avoid any parsing overhead?

Now if we replace the int.Parse() statement by a silly integer operation, such as
intList = intvalues.Select(p => p -1 ).ToList(); we have to increase the loopcount to 10,000,000 to get the workload to any significance. Now we measure plain LINQ performance.

x64 results:
Test 1) 269 ms
Test 2) 125 ms
Test 3) 128 ms

x86 results:
Test 1) 276 ms
Test 2) 126 ms
Test 3) 121 ms

Conclusion:
I expect over time that compilers become more and more smarter and can optimize even better LINQ expressions. 
However, as we saw in the first example, int.Parse already flattened the results and the relative slowness of LINQ greatly.
Parsing and converting data in loops, is something we constantly do when we deal with XML and databases. So when the workload within the loop increases, the overhead of LINQ expressions quickly become no important factor. 

So, for shorter code, I would not hesitate to use those expressions as in Test 1.
In a real life business application, the performance of loops really does not determine the final user experience. It is (e.g.) how we access a database or other resources, such as XML.

It would be another story, if we e.g. were doing 3D math animations, where C++ would be an obvious choice.

 

Howto program a LINQ expression which effectively does an aggregate subquery with optional cardinal relationship 0 Reacties

LINQ! Yes, Also I fell in love with linq. 

So here is my first try. And as you fans know, I like to dig into subjects.

Maybe, the title is a little incorrect, but I wanted a query that returns one record, using a subquery in one statement!

Using SQL syntax, this would look like the query just below.: Yes, It seems I can dream SQL, but it was shocking to see how I underestimated the LINQ syntax which took some extra hears from my head.

The query returns events, that have not already been booked full. (There are still some places left)

SELECT [t0].[id], [t0].[maxNumberofParticipants], [t0].[OwerId], [t0].[Description], [t0].[StartTime], [t0].[EndTime],
[t0].[orderId] FROM [dbo].[Activity] AS [t0]
WHERE ([t0].[OwerId] = @p0) AND ([t0].[maxNumberofParticipants] > @p1) AND ([t0].[maxNumberofParticipants] > (ISNULL((
    SELECT SUM([t2].[value])
    FROM (
        SELECT [t1].[countOfPersons] AS [value], [t1].[activityId]
        FROM [dbo].[ActivityParticipant] AS [t1]
        ) AS [t2]
    WHERE [t2].[activityId] = [t0].[id]
    ),0)))

I could make this a stored proc, and execute this easily. But that was in my previous life.

So, how to express this using a LINQ query?

The trick with the ISNULL function is to -cast- the countOfPersons field, to a nullable type! Since the GetValueOrDefault() is available only to nullable data types we must cast it to an int? datatype.
The LINQ provider, will translate it finally, when it sends the actual SQL to SQL Server using TSQL function 'COALESC'.
bt.w., it will not use the ISNULL function. 

public IEnumerable<Activity> getActivityParticipableByOwnerWith(Guid ownerGuid)
{

var query = from a in Activities
where a.OwerId == ownerGuid && a.maxNumberofParticipants > 0 && a.maxNumberofParticipants >
ActivityParticipants.Where(aid => aid.activityId == a.id).Sum(aid => (int?)aid.countOfPersons).GetValueOrDefault(0)
select a ;
 

return query;
}

Kuddo's to Khaled Moawad, who very patiently helped me to improve the syntax.  b.t.w. guys/girls. Always try it hard yourself, before you ask the global community for support. That makes your brains retain better :)

My next goal is to make LINQ like a natural language for me, like SQL was :)

Howto loop through each element on a SafeArray with an unknown number of Dimensions?0 Reacties

I thought that the subject ‘SafeArrays’ were really from the previous age and there was really nothing new about them, I could tell you , that was not already known.

So sit back and listen, what I am going to tell you, has been decided, in a dark hole, were some Microsoft Nerds Surprise must have thought that our programmers' live was too easy. So they modified the way the old variant arrays from the COM era were stored in memory.

Which Windows editions are involved in this modification? I don't know exactly. Anyway, Windows 64 bit edition (x64) really is subject to this, while Windows 2003 x86 (32 bit) is not. And don't worry too much, if you only use Ole Automation API calls, and not like I did, directly manipulated the SAFEARRAY storage area, your hard working code at your customers site, still should work Smile

So, let’s figure what has changed by looking at the code below which very common.

SAFEARRAYBOUND bounds[1];

bounds.cElements = 10;
bounds.lLbound = 0;

SAFEARRAY *psa = SafeArrayCreate(VT_VARIANT, 1, &bounds);

This creates a variant array, that is compatible with scripting, similar to
Redim myArray(9) ' 0 to 9 is ten elements.

But before the array storage memory layout modification that I'm talking about,

LONG elSize = SafeArrayGetElementSize(psa); would return 16 (since sizeof(VARIANT) obviously equals that) but on Windows x64, this returns 24. Possibly, the alignment still is 16, but this makes me suspicious. Why did Microsoft change this? So I want to be sure it works independently of the Windows version or future features. 

// code below gives an impression how to loop through an ‘unknonn dimension sized Safe Array, in this case the variant type is VT_VARIANT. Don’t use it. It’s faulty now on modern Windows systems.

LONG lElements  = 0; 

for (LONG x = 0; x < cDims; x++)

{

      SafeArrayGetLBound(psa, x + 1, &lbound);

      SafeArrayGetUBound(psa, x + 1, &ubound);

      lElements += (ubound - lbound + 1);

 } 

hr = SafeArrayAccessData(psa, &psadata);
if (hr == S_OK)
{
                VARIANT *myvarray = static_cast<VARIANT *>(psadata);
                for (LONG els = 0; els < lElements && hr == S_OK; els++)
                {              // do something easy with the element
                               VARTYPE vt = myvarray[els].vt;
                }
                SafeArrayUnaccessData(psa);
}
The code above, would work to go through all elements for –any type of-SafeArray, VT_UI1, VT_BSTR, VT_VARIANT, because we assumed, for instance, that a VT_UI1, would be one byte long, isn’t it? And a BSTR Safe Array, would be a memory block, of BSTR pointers. And a VARIANT array, would have been a block of elements, consisting of VARIANTS.

So the code above, just worked, and looks in fact, pretty simple, fast and elegant.
Why so? Because it avoided the task to construct the indices one by one, and to fetch the element by using SafeArrayGetElement(psa, rgindices, outputvalue).


This one surely works, but has two important disadvantages,
1) when you deal with a known 3D or 2D sized-array, it's easy to fill the rgIndices in a loop, but if the dimensions are unknown, it would be required to iterate through the elements by other means. So  you’re up to do some nasa stuff!
J
.
2)  SafeArrayGetElement is relatively slow, since it copies the out value and you need to release the output (such as variants and strings). It’s like pumping around lots of memory, especially when the array is huge.

To get this working, I had to refresh my knowledge of some informatics school I did in the past, about simple math, about carry over on signed numbers. Since SafeArrays have different lowerbounds and upperbound ranges per dimension, you cannot simply multiply by a known row size, to initialize it. But anyway, to make a longer story shorter, and I might lack the correct choice of words, for things that I technically just ‘see’, I wrote the code for you. It’s pretty cool, I could not find such code through Google. J
Some tips. I decided to avoid reading the pointer to the safearray descriptor at all, because I saw some unexplainable swapping of rgsaBounds. Better use the API if there is one!

// assume psa to be of SAFEARRAY and this code is using ATL version 8

LONG cDims = SafeArrayGetDim(psa);

//we ‘rebuild’ the bounds by using the API, not by reading the psa structure directly to avoid unclear behaviour
CTempBuffer<SAFEARRAYBOUND> psaBound(cDims);

CTempBuffer<LONG> rgIndices(cDims);

LONG dimPointer = 0; // our dimension pointer, we go from left to right to build up the rgIndices

LONG currentEl = 0, ubound, lbound;

for (LONG x = 0; x < cDims; x++)

{

      SafeArrayGetLBound(psa, x + 1, &lbound);

      SafeArrayGetUBound(psa, x + 1, &ubound);

      psaBound[x].cElements = ubound - lbound + 1;

      psaBound[x].lLbound = rgIndices[x] = lbound;

}

// locking is not optional, it is needed.

SafeArrayLock(psa);

for(;;) //termination is decided within the loop

{

      if (rgIndices[dimPointer] <

            (LONG)psaBound[dimPointer].cElements + psaBound[dimPointer].lLbound)

      {

            VARIANT* pVar ;

            // use the fast version instead of SafeArrayGetElement!

            hr = SafeArrayPtrOfIndex(psa, rgIndices, (void**)&pVar);

            if (FAILED(hr))

                  MYBAILOUT(hr);

            rgIndices[dimPointer]++;

            //this terminates the for as soon as we reached the last array element

            if (++currentEl == lElements)

                  break;

      }

      // our carry on overflow stuff goes from left to right

      else

      {

            while(rgIndices[++dimPointer]++ ==

            (LONG)psaBound[dimPointer].cElements + psaBound[dimPointer].lLbound)

            {

            }

            //reset previous cols to initial lowerbound from left to

            // most right carry position

            for (LONG z = 0; z < dimPointer; z++)

                  rgIndicesPerson = psaBoundPerson.lLbound;

            // if carry has been done, we start counting on left again

            dimPointer= 0;              

      }

}

To visualise this, I think it’s usefull to dry test this using a matrix.

Imagine, we have a script, that was created by your customer, in VBSCript and youre superpower, martian CPP needs to do something with this data.

So, the Customer code could be:

Redim MyArray(3,2)

How would our dynamic rgIndice be iterated?

rgIndices would follow this pattern.

Left dimension

Right dimension

Absolute element position

0

0

0

1

0

1

2

0

2

3

0

3

0

1

4

1

1

5

2

1

6

HttpWebRequest on DotNet 2.0 driving you crazy for a B2B request? Disable ServicePointManager.Expect100Continue first!0 Reacties

Imagine, you have written a succesfull gateway to say, the European Community to check the validity of a VAT number.

It always works, but suddenly it does not work anymore. What's up? Could it be that some service pack modified the behaviour of the HttpWebRequest (including DotNet 2.0?) Sure  it is! see http://support.microsoft.com/kb/915599

This posting might spare you several hours. The idea of the Expect100Continue setting is, that postdata is sent to the webserver in a separate post sequence package. But not all web servers like IIS (sure I'm MVP Big Smile) are full featured so in this case, this feature was hard to detect, only by using Netmon, I could figure what the HttpWebRequest  was doing under the .NET runtime hood.

The Uri to the European VAT check is http://ec.europa.eu/taxation_customs/vies/

And it does a POST request to viesquer.do
(
the previous obsolete URL was  http://europa.eu.int/comm/taxation_customs/vies/cgi-bin/viesquer)

It had worked before because it just dit a GET request instead of a POST.

The steps that I walk through normally to write such a gateway,

  1. opening my browser
  2. Fill the form
  3. Start Netmon 2.1 (or higher)
  4. Post the data
  5. Stop Netmon and filter on the HTTP protocol.

Now it's up to you to emulate the postdata and be sure that the character encoding is according to the supported one. In my case, I assume that UTF-8 is the worldstandard (it should work for most sites).

The code below is technically correct for the mentioned purpose but it performs no validation checking.
If you wish more flexibility some more work has to be done.

static bool doVatCheck(string vat, string state)

        {

            string urlQuery = @"http://ec.europa.eu/taxation_customs/vies/viesquer.do";

            //important! The WebLogic Server 8.1 SP3 clearly does not support IETF RFC 2616 Section 10.1.1.

// so we disable the expect100 header and HTTP behaviour

            ServicePointManager.Expect100Continue = false;

            HttpWebRequest req;

            StreamReader read=null;

          

            Encoding enc = System.Text.Encoding.UTF8;

            MemoryStream sw = new MemoryStream();

            advancePos(enc, sw, "ms"); //member state

            advancePos(sw, '=');

            advancePos(enc, sw, state);

            advancePos(sw, '&');

            advancePos(enc, sw, "iso"); //same as member state, ISO country code

            advancePos(sw, '=');

            advancePos(enc, sw, state);

            advancePos(sw, '&');

            advancePos(enc, sw, "vat"); // 12no VATno. Do not submit dots or spaces

            advancePos(sw, '=');

            advancePos(enc, sw, vat);

            req = (HttpWebRequest)HttpWebRequest.Create(urlQuery);

            req.Method = "POST";

            req.ContentType = "application/x-www-form-urlencoded";

// optional setting, UserAgent. A firewall could block if no browser is detected    

            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";

            long contLen = req.ContentLength = sw.Position;

            Stream str = req.GetRequestStream();

            str.Write(sw.GetBuffer(), 0, (int)contLen);

            str.Flush();

           try

           {

                read = new StreamReader(req.GetResponse().GetResponseStream(), enc);

                string buf = read.ReadToEnd();

                read.Close();

                return buf.IndexOf("Yes, valid VAT number") >= 0;           

            }

            catch (WebException ex)

            {

                //ex.st

                string errr = (urlQuery + ex.Message);

            }

            return false;

        }

static void advancePos(Encoding enc, MemoryStream sw, string val)

        {

            byte[] buf = HttpUtility.UrlEncodeToBytes(val, enc);

            sw.Write(bufje, 0, buf.Length);

        }

        static void advancePos(MemoryStream sw, char val)

        {

            sw.WriteByte((byte)val);

        }

 

ATL: Tiny but good Improvements on Visual Studio Sevice Pack 1 for ATL.0 Reacties

I'm glad to see, that MS still did not get rid of ATL and continued to support us, that's those guys, who think that .NET is really awful, but not the holy grail :)

If you want to see it yourselfs, get a copy of windiff.exe or just run it, and compare your directories. It's a very handy tool, to compare source codes! 

So, I compared some features on ATL. Quickly I found some differences in atlcomcli.h (I did not check everything however) and the improvements are OK!

Another part of the ATL source code, seems related to HTML and internet (ISAPI). Lots of checks and code has been added to make sure your precious HTML / encoding etc is kept in tact. 

Well, which improvements? As you might know that ATL is all, mainly about writing non-UI unmanaged code, such as COM components or using powerfull small sized wrappers around kernel-items like security, string management, etc.

At first, finally, I found that MS recognized that SafeArrayGetVartype is flawed, since it does not really fetch the VARTYPE of the array in all situations. So they wrote AtlSafeArrayGetActualVartype.

Another things is CComVariant::Clear() which was a dangerous function to use! Why and when? Because the function it wraps, is VariantClear and variantClear does only set vt to VT_EMPTY, but it does not 'zero' the rest of the VARIANT struct. Some programs, do expect in/out variables, and in the case that it is not always testing for the vt (variant type) and reallocates the CComVariant instance, it might erronously reallocate 'freed' or 'zombie'-pointers.

So my advise is to never use CComVariant::Clear() but use CComVariant::ClearToZero() now to avoid a case of reallocating zombie data!

Another handy improvements is a new overloaded method on the WriteToStream member function.
It is CComVariant::WriteToStream(IStream *pstr, VARTYPE vt);

So, if you write the current variant to a certain stream, you can convert it to a BSTR (for instance) using this extra new parameter..

Then we got some important bugfixes in atldb.h and atldbcli.h some annotation and datatype and even template fixes.

Lets see atlutil.h. Lots of new helper functions have been added. AtlStrToNum and functions that help to convert and to support the conversion to and from __int64 (LONGLONG) datatype. Normally, I always had to lookup for such functions into the VC function library and to add some wrappers around them.

Once I checked this all, and I recompiled one of my CPP, ATL projects, the size became just slightly bigger. But who cares? If this is all about more robust and safe code, I'm not disappointed by the Sp1 for VC on Visual Studio 2005.

 

(I was disappointed, when MS deprecated a lot of syntax without any announcements since of Visual Studio 2003)

HOWTO: Associate a custom WKGUID (well known guid) to a custom Container0 Reacties

Active Directory and ADSI (ldap in fact) have many unutilized features that, if the APIs would explain better be used much better!

Let me draw a situation for you.

Imagine you have an app, that is distributed and sold among international customers (congrats for that by the way J). Now there could happen 2 things, or 3 if nothing happens is a count as well).

1)      Your company suddenly got sold out to a rich guy or girl and now everything gets renamed including your ‘custom company container’.
So cn=ourcompany data,cn=Program Data,dn=nwtraders,dc=msft
Must become (because your boss asks you to do so!)
cn=thenewcompany data,cn=Program data,dn=nwtraders,dc=msft

2)      Some dn (distinguished Name) is subject to translation. Eg:
cn=Program Information,cn=etc blah blah
must be translated (because your boss asks you to do so
J ) to
cn=Information du programme,cn=etc blah blah

In both situations 1 and 2 you’ll have to keep a list of paths per language and many companies of course, understand this is a difficult and risky task, so they might choose to keep up with a single international English name.

Note: The WKGUID protects against renaming or translating, but it is not meant to ‘protect’ against moving your container within Active Directory)

Why should you accept this risk if Active Directory supports immunity against renaming this out of the box if you associate a WKGUID?

However there is no obvious documentation about this and you just should know that setting this property more or less is hidden through usage of IDirectoryObject while ADSI /scripting/vb6 environments were not able to use this interface. 

Worse, the sample at the MSDN might be working but goes lowest by using the ldap_connect API within a ADSI call (that’s rather dirty) instead of using CLSID_DNWithBinary and the sample is flawed with leaks but let’s not bash the writer, I’m not intending to do so).

(update) b.t.w. in the attachment temp.zip you'll find full source code for the sample. Note that Active Directory has a bug that makes custom WKGUIDs useless. It simply cannot find your custom WKGUID. I reported this bug to Microsoft.

How could you ever figure that WKGUID and it’s query syntax is related to the following attribute: ‘otherWellKnownObjects’?J.

This sort of documentation, it's complexity in Active Directory on LDAP makes it hard to see any utilization for this feature.

I hope to support MS-es Active Directory (that I love, just as IIS and SQL server) usage and ease in practice by posting the following sample code.

Note that this code is not ‘well-formed’ and ‘error-proof’ but it works and gives you an idea.

The logging (debug feature) is done through the logging module posted just before this posting.

Now how do we profit from this feature?

Imagine you have created through an LDIF or through code a container object

cn=our CompanyData,cn=Program Data,dc=nwtraders,dc=msft

1)      Now we associate ‘our CompanyData’ with the ‘otherWellKnownObjects’ property using a custom hexadecimal guid  81a3469a653959419309b33e27bdd2c9”!

2)      Eg: WriteADSAttributeDnWithString([ourcompnayCN], L”cn=our Company Data,cn=Program Data,dc=nwtraders,dc=msft”, ourGUID, ADS_ATTR_APPEND

3)      Now you can query your company data like this, no matter your company is being renamed in futureJ, through the following syntax: LDAP://<WKGUID=8a3469a653959419309b33e27bdd2c9,cn=Program Data,dc=nwtraders,dc=msft>

Normally the dn for Program Data is WKGUID-ed by Microsoft as well! The Program Data container should be reliably formatted as L"LDAP://<WKGUID=%s,%s>", GUID_PROGRAM_DATA_CONTAINER_W, L”dc=nwtraders,dc=msft”)

Note: After you usage of the WKGUID or the GUID- syntax, you must resolve the fully qualified dn by using the ‘distinguishedName’ property and refetching your Actife Directory object before you go on with it.

 


Note: You would wish you could set the objectGUID attribute at creation of your object instead of the WKGUID. Unfortunately, this value is generated by Active Directory itself.)

STDMETHODIMP WriteADSAttributeDnWithString(

IADs *piADs,

PCWSTR dn,

PCWSTR guid)

{

      CComVariant v;

     CComPtr<IADsDNWithBinary> dnWithBin;

      CComBSTR assocDn(dn);

     dnWithBin.CoCreateInstance(CLSID_DNWithBinary);

      v.vt = VT_UI1 | VT_ARRAY;

hr = ConvertHexGuidToArray(guid, &v.parray);

      hr = dnWithBin->put_BinaryValue(v);

      hr = dnWithBin->put_DNString(assocDn);

CComBSTR attribute( L"otherWellKnownObjects");

     

v.Clear();

      v.vt = VT_DISPATCH;          

      dnWithBin.QueryInterface(&v.pdispVal);

      hr = pADs->Put(attribute, v);

      hr = pADs->SetInfo();

     

      return hr;

}

// converts hexadecimal string to a octet encoded byte array

STDMETHODIMP ConvertHexGuidToArray(PCWSTR hexGuid, LPSAFEARRAY *sa)

{

      if (hexGuid == NULL) return E_INVALIDARG;

      int hexLen = (int)wcslen(hexGuid);

      HRESULT hr = S_OK;

      CTempBuffer<CHAR> sHex(hexLen);

      int loopLen = hexLen;

      while(loopLen-- != 0)  

            sHex[loopLen] = (CHAR) hexGuid[loopLen];

      SAFEARRAY *temp= SafeArrayCreateVector(VT_UI1, 0, hexLen / 2);

      if (temp == NULL)

            return E_OUTOFMEMORY;

      PBYTE dst ;

      hr = SafeArrayAccessData(temp, (void**)&dst);

      int dstLen = hexLen /2;

      if (hr == S_OK)

      {

            AtlHexDecode(sHex, hexLen, dst, &dstLen );

            hr = SafeArrayUnaccessData(temp);

            *sa = temp; //return the array

      }

      return hr;

}


© 2018 - 2020 Adc Cure