Joseph Michael Pesch
VP Programming

Asp.Net GetCurrentPageName

by 10. November 2010 18:32

static public string GetCurrentPageName()
{
  System.IO.FileInfo fi = 

    new System.IO.FileInfo(HttpContext.Current.Request.Url.AbsolutePath);
  return fi.Name;
}

 

Tags:

[None]

Outlook 2007 URL Protocol Registry Entry

by 10. November 2010 14:14

Registering Outlook 2007 to a URL Protocol.zip (126.05 kb)

Contents of a registry edit file for 2007:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\outlook]
"URL Protocol"=""
@="URL:Outlook Folders"
[HKEY_CLASSES_ROOT\outlook\DefaultIcon]
@="\"C:\\Program Files\\Microsoft Office\\Office12\\OUTLOOK.EXE\""
[HKEY_CLASSES_ROOT\outlook\shell]
@="open"
[HKEY_CLASSES_ROOT\outlook\shell\open]
@=""
[HKEY_CLASSES_ROOT\outlook\shell\open\command]
@="\"C:\\Program Files\\Microsoft Office\\Office12\\OUTLOOK.EXE\" /select \"%1\""

Modified for 2010 on 64bit machine running Office on x86:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\outlook]
"URL Protocol"=""
@="URL:Outlook Folders"
[HKEY_CLASSES_ROOT\outlook\DefaultIcon]
@="\"C:\\Program Files (x86)\\Microsoft Office\\Office14\\OUTLOOK.EXE\""
[HKEY_CLASSES_ROOT\outlook\shell]
@="open"
[HKEY_CLASSES_ROOT\outlook\shell\open]
@=""
[HKEY_CLASSES_ROOT\outlook\shell\open\command]
@="\"C:\\Program Files (x86)\\Microsoft Office\\Office14\\OUTLOOK.EXE\" /select \"%1\""

Tags:

[None]

Visual Studio 2010 Resources

by 10. November 2010 13:28

The Visual Studio "Productivity Power Tools" are a set of Visual Studio addins that offer enhanced develeper experience in the IDE.  For example, there are features such as the following.  Enhanced tab well, allowing colorization of tabs by file type, alternative tab docking points (i.e. left side vertical tab set, vs. standard top horizontal).  Javascript code auto-collapse regions, similar to the auto-collapse feature on the C#/VB code behind.  Quick find, which allows a more user friendly find/replace, that works similar to a modern web page find (i.e. auto-highliting matches dynamically as you type), along with enhanced regular expression support.  These are just a few examples of some of the great enhanced features provdided in the "Productivity Power Tools". 

To view more details and download the bits, check out this web site: http://visualstudiogallery.msdn.microsoft.com/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef

Tags:

[None] | Visual Studio

Windows Phone 7 Development

by 10. November 2010 13:27

Tags:

[None]

MSI Installation Error: The installer was interrupted before <product> could be installed

by 8. November 2010 21:23

Issue: When you run the msi, you get an error 'The installer was interrupted before <product> could be installed.  You need to restart the installer to try again'. 

Solution:

In order to install a web setup project on Windows Server 2008 and IIS 7, you need to install the IIS 6 Metabase Compatibility role service.

 

To install the IIS 6.0 Management Compatibility Components by using the Windows Server 2008 Server Manager

1.     Click Start, click Administrative Tools and then Server Manager.

2.     In the left navigation pane, expand Roles, and then right-click Web Server (IIS) and select Add Role Services.

3.     On the Select Role Services pane, scroll down to IIS 6 Management Compatibility.

4.     Select the check boxes for IIS 6 Metabase Compatibility and IIS 6 Management Console.

5.     Click Next from the Select Role Services pane, and then click Install at the Confirm Installations Selections pane.

6.     Click Close to leave the Add Role Services wizard.

Tags:

[None]

Sample Code Re-write with Generics

by 8. November 2010 15:18

    public string GetCampaign(string campaigncode)

    {

      System.Diagnostics.Debug.WriteLine("inside GetCampaign");

 

      // NEW

      List<campaign> camp = Crm.GetEntityList<campaign>(Crm.BuildStringQuery(

        EntityName.campaign.ToString(), "codename", ConditionOperator.Equal, campaigncode

        , LogicalOperator.And, new string[] { "campaignid", "codename", "name" }));

      return camp.Count == 1 ? camp[0].campaignid.Value.ToString() : "";

 

      // OLD

      ColumnSet cols = new ColumnSet();

      cols.Attributes = new string[] { "campaignid", "codename", "name" };

 

      ConditionExpression[] condition = new ConditionExpression[1];

      condition[0] = new ConditionExpression();

      condition[0].AttributeName = "codename";

      condition[0].Operator = ConditionOperator.Equal;

      condition[0].Values = new string[] { campaigncode };

 

      FilterExpression filter = new FilterExpression();

      filter.FilterOperator = LogicalOperator.And;

      filter.Conditions = condition; //new ConditionExpression[] {condition};

      QueryExpression query = new QueryExpression();

      query.EntityName = EntityName.campaign.ToString();

      query.ColumnSet = cols;

      query.Criteria = filter;

 

      // Retrieve the ServiceAppointments

      BusinessEntityCollection lines = Crm.GetCrmService().RetrieveMultiple(query);

 

      //retrieve into an object

 

      int NumOfLines = lines.BusinessEntities.Length;

      string campid = "";

      System.Diagnostics.Debug.WriteLine("numoflines = " + NumOfLines);

      campaign[] campretrieved = new campaign[NumOfLines];

 

      if (NumOfLines > 1 || NumOfLines < 1)

      {

        System.Diagnostics.Debug.WriteLine("more than one record matched");

        campid = "";

      }

      else

      {

        System.Diagnostics.Debug.WriteLine("found matching contact record");

        int i = 0;

        campid = "";

 

        while (i < 1)

        {

          campretrieved[i] = (campaign)lines.BusinessEntities[i];

          campid = campretrieved[i].campaignid.Value.ToString();

          i++;

        }

      }

      //System.Diagnostics.Debug.WriteLine("campid = " + campid);

      return campid;

    }

 

Tags:

[None]

Invalid postback or callback argument ASP.Net

by 4. November 2010 15:29

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

This can happen if you are binding a GridView control on page load unconditionally (i.e. it should only be bound when !Page.IsPostBack).

Tags:

ASP.Net

MS CRM Lookup Field DataValue Property JavaScript

by 3. November 2010 17:41

var lookupItem = new Array;

 

// This will get the lookup for the attribute primarycontactid on the Account form.

lookupItem = crmForm.all.primarycontactid.DataValue;

 

// If there is data in the field, show it in a series of alerts.

if (lookupItem != null)

{

   // The text value of the lookup.

   alert(lookupItem[0].name);

 

   // The GUID of the lookup.

   alert(lookupItem[0].id);

 

   // The entity type name.

   alert(lookupItem[0].typename);

 

   // The entity type code of the lookup: 1=account, 2= contact.

   // This attribute is deprecated. Use typename instead.

   alert(lookupItem[0].type);

}

 

 

Tags:

[None]

MS CRM GetBusinessEntity JavaScript SOAP Call

by 3. November 2010 17:33

window.IsNull = IsNull;

function IsNull(value) {

  return (typeof value == 'undefined' || value === null);

}

 

window.GetBusinessEntity = GetBusinessEntity;

function GetBusinessEntity(sEntityname, sAttribute, sLookupValue) {

  var xml = "" +

  "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +

  "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +

  " <soap:Body>" +

  " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\" xmlns=\"http://schemas.microsoft.com/crm/2006/WebServices\">" +

  " <q1:EntityName>" + sEntityname + "</q1:EntityName>" +

  " <q1:ColumnSet xsi:type=\"q1:AllColumns\" />" +

  " <q1:Distinct>false</q1:Distinct>";

  if (!IsNull(sAttribute)) {

    xml +=

    " <q1:Criteria>" +

    " <q1:FilterOperator>And</q1:FilterOperator>" +

    " <q1:Conditions>" +

    " <q1:Condition>" +

    " <q1:AttributeName>" + sAttribute + "</q1:AttributeName>" +

    " <q1:Operator>Equal</q1:Operator>" +

    " <q1:Values>" +

    " <q1:Value xsi:type=\"xsd:string\">" + sLookupValue + "</q1:Value>" +

    " </q1:Values>" +

    " </q1:Condition>" +

    " </q1:Conditions>" +

    " </q1:Criteria>";

  }

  xml +=

  " </query>" +

  " </soap:Body>" +

  "</soap:Envelope>" + "";

 

  var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

  xmlHttpRequest.Open("POST", "/mscrmservices/2006/CrmService.asmx", false);

  xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2006/WebServices/RetrieveMultiple");

  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);

  xmlHttpRequest.send(xml);

  return xmlHttpRequest.responseXml;

 

}

 

window.GetBusinessEntitySample = GetBusinessEntitySample;

function GetBusinessEntitySample() {

 

  var xml;

 

  // Get a specific Business Entity by Id

  xml = GetBusinessEntity('new_lkploantransactiondispotype', 'new_lkploantransactiondispotypeid', 'A73110D8-A4E6-DF11-8A19-0050568619C7');

  alert('The name of selected id search is: ' + xml.selectNodes("//BusinessEntity")[0].selectSingleNode("./q1:new_name").text);

 

  // Get a specific Business Entity by Name

  xml = GetBusinessEntity('new_lkploantransactiondispotype', 'new_name', 'Lead');

  alert('There id of the selected name search is: ' + xml.selectNodes("//BusinessEntity")[0].selectSingleNode("./q1:new_lkploantransactiondispotypeid").text);

 

  // Get all active Business Entities

  xml = GetBusinessEntity('new_lkploantransactiondispotype', 'statuscode', '1');

  var nodeList = xml.selectNodes("//BusinessEntity");

  var msg = 'There are : ' + nodeList.length + ' active entities';

  for (i = 0; i < nodeList.length; i++) {

    rsName = nodeList[i].selectSingleNode("./q1:new_name").text;

    rsGuid = nodeList[i].selectSingleNode("./q1:new_lkploantransactiondispotypeid").text;

    msg += '\r\n' + rsGuid + ": " + rsName

  }

  alert(msg);

 

  // Get all Business Entities

  xml = GetBusinessEntity('new_lkploantransactiondispotype');

  var nodeList = xml.selectNodes("//BusinessEntity");

  var msg = 'There are : ' + nodeList.length + ' total entities';

  for (i = 0; i < nodeList.length; i++) {

    rsName = nodeList[i].selectSingleNode("./q1:new_name").text;

    rsGuid = nodeList[i].selectSingleNode("./q1:new_lkploantransactiondispotypeid").text;

    msg += '\r\n' + rsGuid + ": " + rsName

  }

  alert(msg);

 

}

 

 

 

Tags:

[None]

ASP.Net Diagnostics Trace Listners (Text File and Event Log Samples)

by 1. November 2010 15:25

public static class Logging

{

 

  public static void AddTextWriterTraceListener()

  {

    string TempPath = Path.GetTempPath();

    TempPath = ConfigurationManager.AppSettings["LogPath"];

    if (!TempPath.EndsWith("\\")) TempPath += "\\";

    AddTextWriterTraceListener("UNDEFINED", TempPath

      + "Global.Logging.TextWriterTraceListener."

      + DateTime.Now.ToString("yyyyMMdd-hhmm")

      + ".txt");

  }

  public static void AddTextWriterTraceListener(string ApplicationName)

  {

    string TempPath = Path.GetTempPath();

    TempPath = ConfigurationManager.AppSettings["LogPath"];

    if (!TempPath.EndsWith("\\")) TempPath += "\\";

    AddTextWriterTraceListener(ApplicationName, TempPath

      + "Global.Logging.TextWriterTraceListener."

      + ApplicationName + "."

      + DateTime.Now.ToString("yyyyMMdd-hhmm")

      + ".txt");

  }

  public static void AddTextWriterTraceListener(string ApplicationName, string TextLogFilePath)

  {

    TextWriterTraceListener txtlog = new TextWriterTraceListener(TextLogFilePath);

    System.Diagnostics.Debug.Listeners.Add(txtlog);

  }

  public static void AddEventLogTraceListener()

  {

    AddEventLogTraceListener("Global.Logging.EventLogTraceListener.UNDEFINED");

  }

  public static void AddEventLogTraceListener(string ApplicationName)

  {

    EventLogTraceListener applog = new EventLogTraceListener("Application");

    applog.Name = ApplicationName;

    System.Diagnostics.Debug.Listeners.Add(applog);

  }

}

Tags:

[None]

C# Character Code Example

by 24. October 2010 13:27

for (int i = 48; i <= 57; i++) // 0 through 9

  System.Diagnostics.Debug.WriteLine((char)i);

for (int i = 65; i <= 90; i++) // A through Z

  System.Diagnostics.Debug.WriteLine((char)i);

for (int i = 97; i <= 122; i++) // a through z

  System.Diagnostics.Debug.WriteLine((char)i);

 

Tags:

C#

MS CRM Set Lookup Value

by 15. October 2010 17:26

new_contactresearchphone entity = new new_contactresearchphone();

// Set new_clientid (contact reference) lookup to value of empty guid

entity.new_clientid = new Lookup { Value = Guid.Empty

, type = EntityName.contact.ToString() };

Tags:

[None]

MS CRM Set Picklist Value

by 15. October 2010 17:23

// Set new_clienttype picklist value to 2

entity.new_clienttype = new Picklist() { name = "new_clienttype", Value = Convert.ToInt16(2) };

Tags:

MS CRM

Open Excel as .Net DataSet in C#

by 12. October 2010 17:26

This entry shows how to open an Excel file as a standard .Net dataset.  This method uses an OleDb driver provided by Microsoft, it does not require that Excel is loaded on the machine, only the OleDb driver is needed.

 

OleDbConnection con = new OleDbConnection(

  "Provider=Microsoft.ACE.OLEDB.12.0; Extended Properties=Excel 12.0;"

  + "Data Source=" + FilePath);

 

 

Driver Download:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

 

 

static public class ExcelDataSetUtil

  {

 

    static public DataSet GetDataSet(string FilePath, string SheetName, bool HasHeader)

    {

      //OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="

      //                    + FilePath + ";Extended Properties=\"Excel 8.0;"

      //                    + "HDR=" + (HasHeader ? "Yes" : "No") + ";IMEX=1\"");

 

      OleDbConnection con = new OleDbConnection(

        "Provider=Microsoft.ACE.OLEDB.12.0; Extended Properties=Excel 12.0;"

        + "Data Source=" + FilePath);

      con.Open();

      DataSet ExcelDS = new DataSet();

      try

      {

        //Create Dataset and fill with imformation from the Excel Spreadsheet for easier reference

        OleDbDataAdapter cmd = new OleDbDataAdapter(" SELECT * FROM [" + SheetName + "$]", con);

        cmd.Fill(ExcelDS);

        con.Close();

      }

      catch (Exception ex)

      {

        System.Diagnostics.Debug.WriteLine(ex.ToString());

        throw;

      }

      finally

      {

        con.Close();

      }

      return ExcelDS;

    }

 

    static public void GetDataSet_SampleProcessing(string FilePath, string SheetName, bool HasHeader)

    {

      DataSet ExcelDS = GetDataSet(FilePath, SheetName, HasHeader);

 

      try

      {

        //Travers through each row in the dataset

        foreach (DataRow row in ExcelDS.Tables[0].Rows)

        {

          //Stores info in Datarow into an array

          Object[] cells = row.ItemArray;

          //Traverse through each array and put into object cellContent as type Object

          //Using Object as for some reason the Dataset reads some blank value which

          //causes a hissy fit when trying to read. By using object I can convert to

          //String at a later point.

          foreach (object cellContent in cells)

          {

            //Convert object cellContect into String to read whilst replacing Line Breaks with a defined character

            string cellText = cellContent.ToString();

            cellText = cellText.Replace("\n", "|");

            //Read the string and put into Array of characters chars

            System.Diagnostics.Debug.WriteLine(cellText);

          }

        }

      }

      catch (Exception ex)

      {

        System.Diagnostics.Debug.WriteLine(ex.ToString());

        throw;

      }

    }

  }

 

 

Tags:

[None]

Slow SSIS Package

by 11. October 2010 21:22

http://www.sqlmonster.com/Uwe/Forum.aspx/sql-server-dts/8025/SSIS-OleDB-source-as-table-view-Hideously-Slow

The difference between my SSIS package and the Export Wizard's package was
that the wizard chose an "Sql command" Data Access Method (and simply said
SELECT * FROM view)  where I chose the "Table / View" Data Access Method.

The type of Data Access Method selected apparently makes a HUGE difference
in response time.

Tags:

[None]

JavaScript Payment Calculator

by 17. September 2010 18:33

double xpmt = pv * (rate / (1 - Math.Pow(1 + rate, -nper)));

Tags:

[None]

HTML JavaScript Web Service Call

by 17. September 2010 14:56

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

  <title></title>

  <script type="text/javascript">

    function MakeSoapCall(WebServiceUrl, Namespace, WebMethod, WebMethodParams) {

      var xmlHttp;

      function SoapCall() {

        // creatng the xmlHttp object

        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

        // Calling the web service using post and true means asynchronous call

        // WebServiceUrl Sample: http://localhost/MyWebService.asmx

        xmlHttp.open("post", WebServiceUrl, true);

        // Setting the request header to let the web service identify the soap request we would be sending

        xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

        // SoapAction Sample: http://MyNameSpace.com/MyWebMethod – name of the webmethod

        // Example: [WebService(Namespace = "http://MyNameSpace.com/")] applied to our web service class

        xmlHttp.setRequestHeader("SOAPAction", "http://" + Namespace + "/" + WebMethod);

        xmlHttp.onreadystatechange = doUpdate;

        // setting the soap request body

        var soapRequest = "<?xml version='1.0' encoding='utf-8'?>" +

          "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +

          " xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +

          "<soap:Body>" +

          "<" + WebMethod + " xmlns='http://" + Namespace + "/'>" +

          WebMethodParams +

          "</" + WebMethod + ">" +

          " </soap:Body>" +

          "</soap:Envelope>";

        // send the request

        document.all('WebMethodParamsTextArea').value = soapRequest;

        xmlHttp.send(soapRequest);

        return false;

      }

      function doUpdate() {

        debugger;

        if (xmlHttp.readyState == 4) {

          var responseXMLResult = xmlHttp.responseXML;

          // var result = responseXMLResult.lastChild.nodeTypedValue;

          alert(responseXMLResult.xml);

        }

      }

      SoapCall();

    }

   

  </script>

</head>

<body>

  <form id="form1" runat="server">

  <div style="font-family: Calibri;">

    <table>

      <tr>

        <td>

          Web Service URL:

        </td>

        <td>

          <input type="text" id="WebServiceUrlControl" size="100" value="http://www.27seconds.com/Holidays/US/Dates/USHolidayDates.asmx" />

        </td>

      </tr>

      <tr>

        <td>

          Namespace:

        </td>

        <td>

          <input type="text" id="NamespaceControl" size="100" value="www.27seconds.com/Holidays/US/Dates" />

        </td>

      </tr>

      <tr>

        <td>

          Web Method:

        </td>

        <td>

          <input type="text" id="WebMethodControl" size="100" value="GetChristmasDay" />

        </td>

      </tr>

      <tr>

        <td valign="top">

          Web Method Paramaters:

        </td>

        <td>

          <textarea id="WebMethodParamsTextArea" rows="5" cols="75">

<year>2010</year>

          </textarea>

        </td>

      </tr>

      <tr>

        <td>

        </td>

        <td>

        </td>

      </tr>

    </table>

    <br />

    <input type="button" value="Make Soap Call" onclick="MakeSoapCall(document.all('WebServiceUrlControl').value, document.all('NamespaceControl').value, document.all('WebMethodControl').value, document.all('WebMethodParamsTextArea').value);" />

  </div>

  </form>

</body>

</html>

 

 

Tags:

HTML | JavaScript

iTextSharp Read Text from PDF

by 15. September 2010 18:14

Tags:

[None]

SQL Script to Document Database Roles/Permissions

by 11. September 2010 05:32

Script to Reverse Engineer SQL Server Object User Permissions

--Written By Bradley Morris (http://www.sql-server-performance.com/articles/dba/object_permission_scripts_p1.aspx)
--In Query Analyzer be sure to go to
--Query -> Current Connection Options -> Advanced (Tab)
--and set Maximum characters per column
--to a high number, such as 10000, so
--that all the code will be displayed.


DECLARE @DatabaseUserName [sysname]
SET @DatabaseUserName = 'user_name_goes_here'

SET NOCOUNT ON
DECLARE
@errStatement [varchar](8000),
@msgStatement [varchar](8000),
@DatabaseUserID [smallint],
@ServerUserName [sysname],
@RoleName [varchar](8000),
@ObjectID [int],
@ObjectName [varchar](261)

SELECT
@DatabaseUserID = [sysusers].[uid],
@ServerUserName = [master].[dbo].[syslogins].[loginname]
FROM [dbo].[sysusers]
INNER JOIN [master].[dbo].[syslogins]
ON [sysusers].[sid] = [master].[dbo].[syslogins].[sid]
WHERE [sysusers].[name] = @DatabaseUserName
IF @DatabaseUserID IS NULL
BEGIN
SET @errStatement = 'User ' + @DatabaseUserName + ' does not exist in ' + DB_NAME() + CHAR(13) +
'Please provide the name of a current user in ' + DB_NAME() + ' you wish to script.'
RAISERROR(@errStatement, 16, 1)
END
ELSE
BEGIN
SET @msgStatement = '--Security creation script for user ' + @ServerUserName + CHAR(13) +
'--Created At: ' + CONVERT(varchar, GETDATE(), 112) + REPLACE(CONVERT(varchar, GETDATE(), 108), ':', '') + CHAR(13) +
'--Created By: ' + SUSER_NAME() + CHAR(13) +
'--Add User To Database' + CHAR(13) +
'USE [' + DB_NAME() + ']' + CHAR(13) +
'EXEC [sp_grantdbaccess]' + CHAR(13) +
CHAR(9) + '@loginame = ''' + @ServerUserName + ''',' + CHAR(13) +
CHAR(9) + '@name_in_db = ''' + @DatabaseUserName + '''' + CHAR(13) +
'GO' + CHAR(13) +
'--Add User To Roles'
PRINT @msgStatement
DECLARE _sysusers
CURSOR
LOCAL
FORWARD_ONLY
READ_ONLY
FOR
SELECT
[name]
FROM [dbo].[sysusers]
WHERE
[uid] IN
(
SELECT
[groupuid]
FROM [dbo].[sysmembers]
WHERE [memberuid] = @DatabaseUserID
)
OPEN _sysusers
FETCH
NEXT
FROM _sysusers
INTO @RoleName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @msgStatement = 'EXEC [sp_addrolemember]' + CHAR(13) +
CHAR(9) + '@rolename = ''' + @RoleName + ''',' + CHAR(13) +
CHAR(9) + '@membername = ''' + @DatabaseUserName + ''''
PRINT @msgStatement
FETCH
NEXT
FROM _sysusers
INTO @RoleName
END
SET @msgStatement = 'GO' + CHAR(13) +
'--Set Object Specific Permissions'
PRINT @msgStatement
DECLARE _sysobjects
CURSOR
LOCAL
FORWARD_ONLY
READ_ONLY
FOR
SELECT
DISTINCT([sysobjects].[id]),
'[' + USER_NAME([sysobjects].[uid]) + '].[' + [sysobjects].[name] + ']'
FROM [dbo].[sysprotects]
INNER JOIN [dbo].[sysobjects]
ON [sysprotects].[id] = [sysobjects].[id]
WHERE [sysprotects].[uid] = @DatabaseUserID
OPEN _sysobjects
FETCH
NEXT
FROM _sysobjects
INTO
@ObjectID,
@ObjectName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @msgStatement = ''
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 193 AND [protecttype] = 205)
SET @msgStatement = @msgStatement + 'SELECT,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 195 AND [protecttype] = 205)
SET @msgStatement = @msgStatement + 'INSERT,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 197 AND [protecttype] = 205)
SET @msgStatement = @msgStatement + 'UPDATE,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 196 AND [protecttype] = 205)
SET @msgStatement = @msgStatement + 'DELETE,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 224 AND [protecttype] = 205)
SET @msgStatement = @msgStatement + 'EXECUTE,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 26 AND [protecttype] = 205)
SET @msgStatement = @msgStatement + 'REFERENCES,'
IF LEN(@msgStatement) > 0
BEGIN
IF RIGHT(@msgStatement, 1) = ','
SET @msgStatement = LEFT(@msgStatement, LEN(@msgStatement) - 1)
SET @msgStatement = 'GRANT' + CHAR(13) +
CHAR(9) + @msgStatement + CHAR(13) +
CHAR(9) + 'ON ' + @ObjectName + CHAR(13) +
CHAR(9) + 'TO ' + @DatabaseUserName
PRINT @msgStatement
END
SET @msgStatement = ''
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 193 AND [protecttype] = 206)
SET @msgStatement = @msgStatement + 'SELECT,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 195 AND [protecttype] = 206)
SET @msgStatement = @msgStatement + 'INSERT,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 197 AND [protecttype] = 206)
SET @msgStatement = @msgStatement + 'UPDATE,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 196 AND [protecttype] = 206)
SET @msgStatement = @msgStatement + 'DELETE,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 224 AND [protecttype] = 206)
SET @msgStatement = @msgStatement + 'EXECUTE,'
IF EXISTS(SELECT * FROM [dbo].[sysprotects] WHERE [id] = @ObjectID AND [uid] = @DatabaseUserID AND [action] = 26 AND [protecttype] = 206)
SET @msgStatement = @msgStatement + 'REFERENCES,'
IF LEN(@msgStatement) > 0
BEGIN
IF RIGHT(@msgStatement, 1) = ','
SET @msgStatement = LEFT(@msgStatement, LEN(@msgStatement) - 1)
SET @msgStatement = 'DENY' + CHAR(13) +
CHAR(9) + @msgStatement + CHAR(13) +
CHAR(9) + 'ON ' + @ObjectName + CHAR(13) +
CHAR(9) + 'TO ' + @DatabaseUserName
PRINT @msgStatement
END
FETCH
NEXT
FROM _sysobjects
INTO
@ObjectID,
@ObjectName
END
CLOSE _sysobjects
DEALLOCATE _sysobjects
PRINT 'GO'
END

Tags:

SQL Server

MS CRM SOAP Call to WebService

by 1. September 2010 21:55

This sample would link to Client Address Zip Code field (onchange event) to find the State that corresponds to the zip code entered.

function Address1_PostalCode_OnChange() {

  var xmlHttp;

  function SoapCall() {

    // Get zip code from screen field

    var oField = event.srcElement;

    var zipCode = "";

    if (typeof (oField) != "undefined" && oField != null) {

      zipCode = oField.value;

    }

 

    // creatng the xmlHttp object

    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

    // Calling the web service using post and true means asynchronous call

    xmlHttp.open("post", "http://mysite.com/ZipCountyWS/ZipCountyWS.asmx", true);

    // Setting the request header to let the web service identify the soap request we would be sending

    xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

    // http://mynamespace.com/GetStateAndCountyByZipCode – name of the webmethod

    //[WebService(Namespace = "http://mynamespace.com/")] which we had applied to our web service class

    xmlHttp.setRequestHeader("SOAPAction", "http://mynamespace.com/GetStateAndCountyByZipCode");

    xmlHttp.onreadystatechange = doUpdate;

    // setting the soap request body

    var soapRequest = "<?xml version='1.0' encoding='utf-8'?>" +

          "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +

          " xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +

          "<soap:Body>" +

          "<GetStateAndCountyByZipCode xmlns='http://mynamespace.com/'>" +

          "<ZipCode>" + zipCode + "</ZipCode> " +

          "</GetStateAndCountyByZipCode>" +

          " </soap:Body>" +

          "</soap:Envelope>";

    // send the request

    xmlHttp.send(soapRequest);

    return false;

  }

  function doUpdate() {

    debugger;

    if (xmlHttp.readyState == 4) {

      var responseXMLResult = xmlHttp.responseXML;

      var result = responseXMLResult.lastChild.nodeTypedValue;

      crmForm.address1_stateorprovince.value = '';

      crmForm.address1_county.value = '';

      if (result.indexOf('UNKNOWN') == -1) {

        crmForm.address1_country.value = 'USA';

      }

      else {

        alert('Please confirm zip code: '

        + crmForm.address1_postalcode.value

        + ' is valid, no county record was found.'

        + '\r'

        + 'If this is a valid zip code please alert the system administrator.'

      );

      }

      crmForm.address1_stateorprovince.value = result.split(':')[0];

      crmForm.address1_county.value = result.split(':')[1];

    }

  }

  SoapCall();

}

 

 

Tags:

JavaScript | MS CRM