Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, March 1, 2017

Convert nullable bool? to bool

I was trying to set up a complex query screen in MVC.  I have some checkboxes which may or may not be used in the query.  I needed to cast the nullable bool to bool


bool newBool = x.HasValue ? x.Value : false;

Source:
http://stackoverflow.com/questions/6075726/convert-nullable-bool-to-bool

Monday, March 28, 2016

How to test if DateTime is null

Pretty straightforward you need to remember that the .Net stack gives any time date variable a min value by default.  You just need to test for the presence of that min value.


if(test.lastupdate == DateTime.MinValue)
{
//your condition
}

Thursday, December 3, 2015

An unhandled exception of type 'SQLite.Net.SQLiteException' occurred in SQLite.Net.Platform.WinRT.DLL

Problem:
My app was trying to read a local copy of SQLite db.  I kept getting this error. It was crazy since the file is present in the project.  Each time I would try to open the file with the connection string I would get this error

Solution:
It was simple enough.  I have forgot to set my Build Action properties on the SQLite db file.  It set to none when it should be set to Content.
Build Action = Content.

Thursday, July 16, 2015

ERROR: ERROR ITMS-90047: "Disallowed paths ( "iTunesMetadata.plist" ) found at: MyNewTool.app"

Solution:

For command line or IDE builds with XamarinVS
  1. Ensure "Project Properties -> iOS IPA Options -> Include Artwork in IPA" is not checked. (Or manually set the BuildIpa and IpaIncludeArtwork properties as mentioned above.)
    image
  2. Build the app.
  3. Submit the .ipa file using Application Loader.
or

<Target Name="_CompileITunesMetadata" DependsOnTargets="_DetectSdkLocations;_DetectAppManifest;_GenerateBundleName;_CompileAppManifest">
  <Message Text="Skipping CompileITunesMetadata task to prevent inclusion of iTunesMetadata.plist in the IPA" />
</Target>


Source:
  1. https://forums.xamarin.com/discussion/40388/disallowed-paths-itunesmetadata-plist-found-at-when-submitting-to-app-store/p1
  2. https://discussions.apple.com/thread/6997898?start=0&tstart=0
  3. https://bugzilla.xamarin.com/show_bug.cgi?id=29180#c0

Friday, June 26, 2015

How to add strikeout/strikethrough to an UITextView

Problem
Had a number of UITextView controls on my Xamarin/C# screen.  Customer asked for one of them to be underlined.  I was unsure of how to accomplish this.

Solution
Fortunately, Guillermo over at Xamarin Forums had a similar solution for UILabel.  Here is my reworked solution.

UITextView aboutTextView = new UITextView(new RectangleF(30,225,280,80));
aboutTextView.TextColor = UIColor.Black;
var attrString = new NSAttributedString("The Text", underlineStyle: NSUnderlineStyle.Single);
aboutTextView.AttributedText = attrString;
aboutTextView.Font = UIFont.SystemFontOfSize(14.0f);
Add(aboutTextView);



Source:
http://forums.xamarin.com/discussion/11584/how-to-add-strikeout-strikethrough-to-an-uilabel

Thursday, May 7, 2015

How to Wrap Text in a Monotouch/Xamarin UILabel

Doing some UI work on our iPhone app and still trying to remember what the UI supports.
I had an issue with how to wrap text in a UILabel field.  Fortunately, Xamarin forums has some great recipes.

What I needed was (UILineBreakMode.WordWrap)

Solution

var descriptionField = new UILabel(new RectangleF(10, 45, 300, 140));
descriptionField.LineBreakMode = UILineBreakMode.WordWrap;
descriptionField.Lines = 10;
descriptionField.BackgroundColor = UIColor.Gray;
Add(descriptionField);


Source:
http://developer.xamarin.com/recipes/ios/standard_controls/labels/uilabel-truncate-wrap-text/

Friday, October 17, 2014

Randomize boolean method in C#

I just saw this slick little trick in a Xamarin class.  Instructor needed to have a sample class randomly return a true or false. 

This is so simple:

public bool IsTrue()
{
return new Random().Next() % 2 == 0;
}

Wednesday, July 16, 2014

Identity Impersonation with Classic ASP

The ideal:

I have written before about using impersonation in IIS.  That was using the tools provided in .Net Framework.  This allows a web application to provide dedicated account access to a database.  Thus the application can prompt a user to login with their Windows credentials and a separate service account can be used to support all data access between that web application and the database.  This makes the application most secure as it restricts database access to a single account.  Auditing also becomes much simpler.

The reality:

Now it is great to think about how easy it is in .Net.  The reality is that there are still classic ASP applications which are simply being ported forward to IIS7/7.5.  I cringe when a customer asks for this.  They can't understand why the software has to be updated.  One issue is impersonation.

I had a customer wanting to port the application forward and just assuming that they could apply all the security "boxes" just like a .Net application.  Sadly this is not the case for classic ASP.  It does not have a native mechanism to support impersonation. 

"As most of you know ASP executes under the guise, typically, of the IUSR_ account in IIS (IIS_IUSRS group for IIS 7) which has a very few permissions to do anything on the system (in most cases anyway). "

So what can you do?  I found some great help from Doug Parsons over at Wrox.com


The fix:

You can write a ActiveX dll which you register on your IIS box.  This dll is then used by your ASP application each time you want to access the database. 

Using Statements
csharp Code:
using System; using System.Runtime.InteropServices;
Class Definition
csharp Code:
namespace Impersonate
{[indent]public class UserLogon
{[indent][DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

[DllImport("advapi32.dll")]
public static extern int ImpersonateLoggedOnUser(IntPtr hToken);

[DllImport("advapi32.dll")]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);

private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;
public void Logon(string strAdminUser, string strAdminPassword, string strAdminDomain)
{
IntPtr hToken;

RevertToSelf();

LogonUser(strAdminUser, strAdminDomain, strAdminPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out hToken);

ImpersonateLoggedOnUser(hToken);

CloseHandle(hToken);
}
public void Logoff()
{
RevertToSelf();
}
[/indent]}
[/indent]}

In the Solution Explorer locate the AssemblyInfo.cs file underneath the Properties folder of your project (you may need to click the 'Show all Files' button at the top of the solution explorer) and open it. Add the following line to the file:


csharp Code:
[assembly: ComVisible(true)]
Hit Ctrl + Shift + B (Build) to create your assembly.

Start* up a Visual Studio Command Prompt which can, typically, be found in Start -- > Programs --> Visual Studio 2008 --> Visual Studio Tools and navigate to the directory where your assembly is (something like: projectDirectory\bin\debug\) and issue the following command: regasm Impersonate.dll /tlb

*if you are running Win7/8 run this prompt with Admin rights

In your ASP editor (I used Notepad) use the following code to test your assembly:

asp Code:
[size=2]<% Option Explicit Dim objLogon, oFs, oTextFile Set objLogon = Server.CreateObject("Impersonate.UserLogon") objLogon.Logon "username", "password", "domainname" Response.Write("Impersonating") set oFs = server.createobject("Scripting.FileSystemObject") set oTextFile = oFs.OpenTextFile("C:\foo.txt", 2, True) oTextFile.Write "This is some data wrote as a domain user" oTextFile.Close set oTextFile = nothing set oFS = nothing objLogon.Logoff Set objLogon = Nothing Response.Write("Done Impersonating") %> [/size]

Most of this is very basic but there are some things to point out here:

  • Make sure that the call to CreateObject for objLogon has the name of your assembly. The format for the name will be Namespace.Class. If you have followed along using my code then the correct name is Impersonate.UserLogon.
  • Provide a valid username, password, and domain. I have not tried to impersonate a Local User but, I assume, you could simply provide the PC name as the domain and have this work.
  • Make sure that you call LogOff so that the thread reverts back to running as the IUSR account.
Provided that you execute this ASP script under the guise of IUSR, under normal circumstances, the call to create a text file in the root of the C drive should fail with an Access Denied error so that is a good case to test out our impersonation assembly. As you can see above, a user is impersonated, a file is wrote, and the user is logged off. If all went according to plan you should now see a text file in the root of your C drive! Obviously I am making the assumption that the domain user you are impersonating has the right to create files in the root of the C drive so adjust this test case accordingly.

Pitfalls and Gotchas
  • If you are running IIS 7 on a x64 platform you may get a cryptic "Active X is unable to Create Object". Before you google the problem first start up inetmgr, and locate the Application Pool that your ASP script is running from, right click on it and select 'Advanced Settings' from the context menu. The second option under the General section is 'Enable 32-Bit Applications'; change the value from False to True. If you still get the error, then Google it ;]
  • For testing purposes, I suggest moving your dll out of your debug directory and into another one and then register the dll from there. The reason for this is if you have to make any changes to the dll you will not be able to rebuild your project since the OS will have a lock on the dll in your bin directory.
  • If you need to make changes to your assembly after you have already registered it issue the following command from a Visual Studio command prompt inside the directory your assembly is registered from: regasm /u Impersonate.dll tlb:Impersonate.tlb Make your changes and then re-register the assembly using the regasm from the main tutorial. If, after you have unregistered the dll you are unable to replace the file (Access is denied because the file is in use by another process) start taskmgr and kill the w3wp.exe process (you will need to tick off the 'Show porcesses from all users' checkbox). You should now be able to replace the file.




Source:
C# rework:
http://p2p.wrox.com/classic-asp-basics/77007-solution-impersonation-classic-asp.html

MSDN Original (VB6)
http://support.microsoft.com/kb/248187/en-us

Tuesday, July 15, 2014

Cool tool for JSON to C# classes

This is a great site which reads your Json stream and recommends a C# class to contain the resulting query in your solution.

http://json2csharp.com/

Code Sample: Return Office element from Json query in Windows Phone

I wanted to capture this deprecated piece of code which I no longer need in my phone app.
We are supplying a list of office specific information to the phone client via a JSON query.

Calling Method:


using System.Net.WebClient;
using Newtonsoft.Json.JsonConvert;

private static Dictionary<int, Office> _officeLookup;
private static List<Office> theOffices = new List<Office>();

WebClient webClient = new WebClient();
webClient.Headers["Accept"] = "application/json";
webClient.DownloadStringCompleted +=
              new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(apiUrl));



private void webClient_DownloadStringCompleted(object sender,             DownloadStringCompletedEventArgs e);
{
      try
      {
           if(e.Result != null)
          {
           var offices = JsonConvert.DeserializeObject<Office[]>(e.Result);
           theOffices = offices.ToList();
           int id = 0;
           foreach(Office office in offices)
           {
                _officeLookup.Add(id,office);
               id++;
             }
          }
         }
         catch (Exception ex)
         {
               //Error handling here
         }


}

Friday, May 9, 2014

How to configure SMTP client to post to directory

Problem:
Needed to set up a webform to post email to a directory vice sending the email.
It is pretty straightforward.
 
Solution:
 
var smtpClient = new SmtpClient();
//Specify the delivery method as pickup
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
//Specify folder for the pickup.
smtpClient.PickupDirectoryLocation = pickupFolder;
 
Source:

Wednesday, May 7, 2014

A System.Resources.MissingManifestResourceException exception occurs when you try to access a localized resource

Problem:
I broke my phone app out into different projects and now have BLL logic in a separate project.  I created a windows phone class library but it did not include the ever handy resources file in the template.  I foolishly copied and pasted from another project into the new project.  I ended up with this error.  This caused me to do some research into this as of yet unknown area to me. 

The resources file was designed primarily to be used for interationalizing projects.  You can create a resource file for each culture in your project.  This way you can share the same enumerations across the project and simply load the page with the resource which matches the culture of the persons brower. 

My mistake was to try and create this by copy and paste.  If you want to do this manually then microsoft provides great instructions on building Satellite assemblies.



The following Al.exe command creates a satellite assembly for the application MyApp from the file strings.de.resources.

al /t:lib /embed:strings.de.resources /culture:de /out:MyApp.resources.dll

Solution:
I simply dropped the resources file and use the add resource element to the project in question.



Source:

http://support.microsoft.com/kb/839861
Creating Satellite Assemblies
http://msdn.microsoft.com/en-us/library/21a15yht(v=VS.100).aspx


Tuesday, April 1, 2014

BitMapImage into a byte array - XAML manipulation

I was messing with a listbox control for my windows phone app and needed to convert a series
of bitmap images.  Found this piece of code to convert the object.  Now I should be able to
use my httppost class to pass the image as a parameter.


public static byte[] ConvertToBytes(this BitmapImage bitmapImage) {    
          byte[] data = null;    
          using (MemoryStream stream = new MemoryStream()) {        
                      WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);        
                      wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);        
                      stream.Seek(0, SeekOrigin.Begin); data = stream.GetBuffer();    
           }    
return data;
}


Source:
http://stackoverflow.com/questions/4732807/conversion-of-bitmapimage-to-byte-array