FCI-Helwan blog

Just another FCI-H weblog

How to create SQL Server Login programmatically?

Q. How to create SQL Server Login programmatically?

I got this question from Daniweb C# forum, and of course when I need to do something against SQL Server object from .net I go to SMO (SQL Server Management Objects) which provides a great functionalities to do anything with SQL Server instead of going on SSMS and create some scripts then embedding them into stored procedure then call it…. off…
Anyway to avoid showing how much I’m talkative…

Create any C# project type (Windows, Class Library or even Console one), add reference to Microsoft.SqlServer.Smo, Microsoft.SqlServer.ConnectionInfo
and Microsoft.SqlServer.SqlEnum
Server sqlServerInstance =
new Server(new Microsoft.SqlServer.Management.Common.ServerConnection(
new System.Data.SqlClient.SqlConnection("Data Source=.;Initial Catalog=Master;Integrated Security=True")));
// your connection string I place mine for illustration..
Login loginObj = new Login(sqlServerInstance, @"DomainName\UserName");
loginObj.DefaultDatabase = "Master";
loginObj.LoginType = LoginType.WindowsUser;
loginObj.Enable();
loginObj.Create("password");
//set the password
//there're many properties to do some tasks related to Login object...

If you used LoginType.WindowsUser, be sure to provide valid windows username and if you aren’t on Domain use the machine name instead.

If you need to create SQL login use LoginType.SqlLogin…

You can explore Login class more on http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.login.create.aspx

 

 

 

Advertisements

April 28, 2009 Posted by | .NET Q and A, C#, Microsoft, SMO, SQL Server | 3 Comments

Twitter Common Friends

For the past couple of months, A lot of people (who I don’t know) have been following my twitter.. Mostly they don’t look like anybody I know, not even Egyptians, & I’m not that popular anyway.. I’m ok with people following me anyway.. My twitter is public, & I’m not planning to change that.. But sometimes I need to know if these are real people who are in my twitter “social network” or just some sort of zombies or bots..

I’ve just created a small app to act like “common friends” in Facebook so I can find out whether I really know them or not.. Actually a couple of these followers are really interesting people & I’m following them now.. The app finds common people you’re follwoing.. not common followers, the followers all is almost the same it just need authentacation..



The application depend on a single twitter API which takes the user name as a parameter & returns an xml (or JSON) file of their freinds for eg these are my friends xml file:

http://twitter.com/statuses/friends/mshady.xml

I used the “XML schema definition” tool (Xsd.exe) to generate the class to use the xml nodes directly as nodes rather than querying the XML document.. I’m such a lazy coder.. I know :D..

Once the xml is deserialised into the users datatype like this:

XmlSerializer oXmlSerializer = new XmlSerializer(typeof(users));
users oUsers1 = (users)oXmlSerializer.Deserialize(
                     XmlReader.Create(@”http://twitter.com/statuses/friends/”+textBox1.Text+“.xml”
                        ));

All you need to do is to find the intersection set between the two list/sets.. & display them
 
The source code & binaries are available here: http://cid-570d40f05cc0dc13.skydrive.live.com/self.aspx/Sample%20Code/TwitterTest.rar

April 12, 2009 Posted by | C#, Tips | 2 Comments

C# 4.0 is not a dream, it is comming :)

I Have Nothing to say, just Check this Link

—— Welcome C# 4.0 ——

July 21, 2008 Posted by | C#, Microsoft | 1 Comment

IComparable Interface.

From The name, this Interface used for comparison. This is the implementation of this interface:

C#:

public interface IComparable
{
int CompareTo(object o);
}

 

vb.net:

Public Interface IComparable
    Function CompareTo(ByVal o As Object) As Integer
End Interface

 

The result of this function is Integer; it returns 0 in similarity, -1 when the first one is smaller and 1 when larger .

Now we don’t need to know who is larger, let’s assume that we have car class, something like that:

C#:

class Car
{

string Name;
int year;
}

vb.net:

Class Car
    Private Name As String
    Private year As Integer
End Class

 

Now we need to sort the cars depends on the creation year, our first step it to implement IComparable interface.

C#:

class Car:IComparable
{

string Name;
int year;
}

vb.net:

class Car:IComparable
{

string Name;
int year;
}

 

Next, we should write an implementation to CompareTo function, something like that:

c#:

int IComparable.CompareTo(object obj)
{
Car temp = (Car)obj;
if(this.year > temp.year)
return 1;
if(this.year < temp.year)
return -1;
else
return 0;
}

 

vb.net:

Private Function CompareTo(ByVal obj As Object) As
Integer Implements IComparable.CompareTo
    Dim temp As Car = DirectCast(obj, Car)
    If Me.year > temp.year Then
        Return 1
    End If
    If Me.year < temp.year Then
        Return -1
    Else
        Return 0
    End If
End Function

 

Anyway, -1 is equals to -100 in return value, this function work with any negative number referring to smaller, any positive number also is accepted instead of 1.

Sort Function:

Assume we have array of numbers, in this case some code like that is applicable.

c#:

Array.Sort(myNumbers);

 

vb.net:

Array.Sort(myNumbers)

 

But if we have array of cars, this will cause error, except if we implementing IComparable interface. in this case the array.sort() will use CompareTo function to sort all array elements. This is better solution than using another function for check and sorting. It is also more readable for people who work with you or read your code.

June 17, 2008 Posted by | C# | 1 Comment

How to make your controls moveable?

Q: How to make your controls moveable?


A: Some people need to add style to their controls to be moveable that’s users can drag and drop them anywhere on the form.So, when user presses on a control and moves the mouse; control location should equal mouse axis.

Some variables used in our code.

/// <summary>
/// Indicates whether control is pressed by mouse or not
/// </summary>
bool IsDraged = false;

/// <summary>
/// Holds the X-coordinate of the control
/// </summary>
int Control_X = 0;

/// <summary>
/// Holds the Y-coordinate of the control
/// </summary>
int Control_Y = 0;

This is the mouse down event handler, we just checked the left button is pressed then set boolean variable IsDraged to true and assigned control location to mouse location.

private void Control_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
IsDraged = true;
Control_X = e.X;
Control_Y = e.Y;
}
}

Just when mouse left button released we set IsDraged to false.

private void Control_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
IsDraged = false;
}
}

Here’s when mouse moves while mouse left button not released yet, the computation used helps controls to move smoothly with the mouse movement.

private void Control_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Control active = (Control)sender;
if (IsDraged)
{
active.Left += e.X – Control_X / 12;
active.Top += e.Y – Control_Y / 12;
Control_X = e.X;
Control_Y = e.Y;
}
}
}

May 16, 2008 Posted by | .NET Q and A, C# | 5 Comments

How to save image in SQL Server database?

Q: How to save image in SQL Server database?

A: It’s the most common question asked in technical forums, the answer is so simply is to convert your image to binary and save the equivalent binary data to the database.

I am expecting you know how to Insert\get data to\from SQL Server.

To convert image to binary you need to write this piece of code

   1: System.IO.FileStream fs = new System.IO.FileStream(@"ImagePath", System.IO.FileMode.Open);
   2:             byte[] imageAsBytes = new byte[fs.Length];
   3:             fs.Read(imageAsBytes, 0, imageAsBytes.Length);
   4:             fs.Close();

You need a table with column of binary\image datatype to be able to insert the equivalent binary data of image.

And what about retrieving binary data to be converted to image

You just need to initiate new Image from MemoryStream object which takes array of bytes as an argument -Array of bytes comes from SQL Server-

1: Image img = Image.FromStream(new System.IO.MemoryStream(imageAsBytes));

April 27, 2008 Posted by | .NET Q and A, C# | 4 Comments

How to bind ComboBox to an array of object?

Q: How to bind ComboBox to an array of object?

A:

Assume we have class like Student class

   1: public class Student
   2:     {
   3:         int id;
   4:  
   5:         public int ID
   6:         {
   7:             get { return id; }
   8:             set { id = value; }
   9:         }
  10:         string firstName;
  11:  
  12:         public string FirstName
  13:         {
  14:             get { return firstName; }
  15:             set { firstName = value; }
  16:         }
  17:         string lastName;
  18:  
  19:         public string LastName
  20:         {
  21:             get { return lastName; }
  22:             set { lastName = value; }
  23:         }
  24:  
  25:         public string FullName
  26:         {
  27:             get { return firstName + " " + lastName; }
  28:         }
  29:  
  30:         public Student(int id, string firstName, string lastName)
  31:         {
  32:             this.id = id;
  33:             this.firstName = firstName;
  34:             this.lastName = lastName;
  35:         }
  36:     }

what we need is to bind an array of Student to ComboBox and let the ComboBox shows the student FullName and bind their IDs to be used later.

So, what we need is to use some ComboBox properties like DisplayMember and ValueMember

   1: Student[] students = new Student[3];
   2:  
   3:             students[0] = new Student(1, "Ramy", "Mahrous");
   4:             students[1] = new Student(2, "FCI", "Helwan");
   5:             students[2] = new Student(3, "X", "Y");
   6:  
   7:             comboBox1.Items.AddRange(students);
   8:             
   9:             comboBox1.DataSource = students;
  10:             comboBox1.ValueMember = "ID";
  11:             comboBox1.DisplayMember = "FullName";

And now, ComboBox shows the FullName without overriding ToString method which is not the solution if we need to bind some properties.

Untitled

April 25, 2008 Posted by | .NET Q and A, C# | Leave a comment

Amazon S3 via C#

Amazon Simple Storage Service (Amazon S3) via C#

Amazon S3 is storage for the Internet. It is designed to make web-scale computing easier for developers. It’s provides a simple web services interface that can be used to store and retrieve any amount of data, at any time, from anywhere on the web.

It uses standards-based REST and SOAP interfaces so it is platform independent and language independent.

It `s commercial but highly scalable, reliable, fast and inexpensive data storage infrastructure.

To know more about its advantage and the cost click here:

http://www.amazon.com/gp/browse.html?node=16427261

I am writing here to give you my experiences and tricks which I faced it when I started in develop the service using Dot Net (C#) and soap.

First trick:

When you work using .Net, you must use WSE 2.0 NOT WSE 3.0 as Amazon support DIME (WSE 2.0) NOT MTOM (WSE 3.0).

Second trick:

You can only using the class System.Web.Services.Protocols.SoapHttpClientProtocol, if you want upload files to AWS (Amazon Web Service) that are less than one Megabytes.

Here is an excellent example that server the required (files less than megabyte) with complete demo code for view and upload files.

http://developer.amazonwebservices.com/connect/entry.jspa?externalID=774&categoryID=55

Third trick:

If your files are bigger than one Megabytes (ten, twenty or may be 50 megabytes), you must to change the class System.Web.Services.Protocols.SoapHttpClientProtocol to Microsoft.Web.Services2.WebServicesClientProtocol . (As mentioned in this link)

http://developer.amazonwebservices.com/connect/entry!default.jspa?categoryID=103&externalID=689&fromSearchPage=true

Then follow the last trick…

Last trick:

You must raise the Timeout property that inherits the Microsoft.Web.Services2.WebServicesClientProtocol (the AmazonS3class if you opened the following example) more time out (this property measures in milliseconds) .

Here it an excellent example that server the required (more than one megabyte) with complete code.

http://developer.amazonwebservices.com/connect/entry!default.jspa?categoryID=47&externalID=690&fromSearchPage=true

The Amazon S3 Developer Guide :

http://docs.amazonwebservices.com/AmazonS3/2006-03-01/

March 27, 2008 Posted by | C#, Tips | 5 Comments

The Singularity Research Development Kit

At Tuesday, February 13, 2007 Shereef Saker has posted article on FCI-H about Singularity: A research OS written in C# while going through Microsoft Student Partners forum I found a post sent by Matthieu Suiche an MSP from France informing about Singularity first release…

Microsoft research page: http://research.microsoft.com/os/singularity/
The Singularity Research Development Kit (RDK) 1.1 is now available for academic non-commercial use. You can download it from CodePlex, Microsoft’s open source project hosting website, here. http://www.codeplex.com/singularity

Overview:
Singularity is a research project focused on the construction of dependable systems through innovation in the areas of systems, languages, and tools. We are building a research operating system prototype (called Singularity), extending programming languages, and developing new techniques and tools for specifying and verifying program behavior.
Advances in languages, compilers, and tools open the possibility of significantly improving software. For example, Singularity uses type-safe languages and an abstract instruction set to enable what we call Software Isolated Processes (SIPs). SIPs provide the strong isolation guarantees of OS processes (isolated object space, separate GCs, separate runtimes) without the overhead of hardware-enforced protection domains. In the current Singularity prototype SIPs are extremely cheap; they run in ring 0 in the kernel’s address space.
Singularity uses these advances to build more reliable systems and applications. For example, because SIPs are so cheap to create and enforce, Singularity runs each program, device driver, or system extension in its own SIP. SIPs are not allowed to share memory or modify their own code. As a result, we can make strong reliability guarantees about the code running in a SIP. We can verify much broader properties about a SIP at compile or install time than can be done for code running in traditional OS processes. Broader application of static verification is critical to predicting system behavior and providing users with strong guarantees about reliability.

March 14, 2008 Posted by | C#, Microsoft | Leave a comment

Save As PDF using C#

Welcome guys , this day we will display an esay way to convert files from any format that Microsoft Office open to PDF file format using simple C# code.

Frist of all you should to install 2007 Microsoft Office Add-in: Microsoft Save as PDF (very small about 934 KB) .

Click here to download it from Microsoft site

After you have finished your setup , you should to have new save as option like the picture .

saveasPDF

Secondly : add this two reference to your DotNet project as you see in this picture .

refrences

Then insert the required namespaces in the project ..

Like here :

using System;

using System.Data;

using System.Text;

using System.IO;

using Microsoft.Office.Interop.Word;

finally : here is the class called Doc2PDFAtServerClass , this class have only one static function word2PdfFcih which have two paramters .

this is a example :

object SourceFileName = “Fci-H.doc” ;

object newFileName = “Fci-H.pdf” ;

static public class Doc2PDFAtServerClass

{

static public void word2PdfFcih(object SourceFileName, object newFileName)

{

//Pid++;

Microsoft.Office.Interop.Word.ApplicationClass MSdoc = null;

//object Source = “d:\\Document” + Pid.ToString(System.Globalization.CultureInfo.CurrentCulture) + “.doc”;

object Source = SourceFileName;

object readOnly = false;

object Unknown = System.Reflection.Missing.Value; //Type.Missing;

object missing = Type.Missing;

try

{

//Creating the instance of Word Application

if (MSdoc == null)

MSdoc = new Microsoft.Office.Interop.Word.ApplicationClass();

MSdoc.Visible = false;

MSdoc.Documents.Open(ref Source, ref Unknown,

ref readOnly, ref Unknown, ref Unknown,

ref Unknown, ref Unknown, ref Unknown,

ref Unknown, ref Unknown, ref Unknown,

ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);

MSdoc.Application.Visible = false;

MSdoc.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize;

object FileName = newFileName;

object FileFormat = WdSaveFormat.wdFormatPDF;

object LockComments = false;

object AddToRecentFiles = false;

object ReadOnlyRecommended = false;

object EmbedTrueTypeFonts = true;

object SaveNativePictureFormat = false;

object SaveFormsData = false;

object SaveAsAOCELetter = false;

//object Encoding = MsoEncoding.msoEncodingUSASCII;

object InsertLineBreaks = false;

object AllowSubstitutions = false;

object LineEnding = WdLineEndingType.wdCRLF;

object AddBiDiMarks = false;

/*

to get more details about SaveAs(…) function and it’s parameter ,read this microsoft’s link

http://msdn2.microsoft.com/en-us/library/aa662158(office.10).aspx

*/

MSdoc.ActiveDocument.SaveAs(ref FileName, ref FileFormat, ref LockComments,

ref missing, ref AddToRecentFiles, ref missing,

ref ReadOnlyRecommended, ref EmbedTrueTypeFonts,

ref SaveNativePictureFormat, ref SaveFormsData,

ref SaveAsAOCELetter, ref /*Encoding*/missing, ref InsertLineBreaks,

ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);

}

catch (FileLoadException e)

{

Console.WriteLine(e.Message + “Error” );

}

catch (FileNotFoundException e)

{

Console.WriteLine(e.Message + “Error”);

}

catch (FormatException e)

{

Console.WriteLine(e.Message + “Error”);

}

finally

{

if (MSdoc != null)

{

MSdoc.Documents.Close(ref Unknown, ref Unknown, ref Unknown);

//WordDoc.Application.Quit(ref Unknown, ref Unknown, ref Unknown);

}

// for closing the application

// WordDoc.Quit(ref Unknown, ref Unknown, ref Unknown);

MSdoc.Quit(ref Unknown, ref Unknown, ref Unknown);

MSdoc = null;

}

}

}

Have fun 😉 ..

March 6, 2008 Posted by | Announcements, C#, Microsoft | 3 Comments