How To Get The Week Of The Year By Using A Custom First Day Of The Week Value



TODO:

Have  you ever wanted to get the week of the year by using a a custom first day of the week?

 

SOLUTION:

var weekOfYear = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
                DateTime.Now,
                CalendarWeekRule.FirstDay,
                DayOfWeek.Monday);


NOTES:

This sample will get the week of the year by using the FirstDay of the week set to Monday, rather than the default of Sunday.

How To Change An Application Pool Username and/or Password Using C#



TODO: 

Have you ever wanted to change the username and password for an Application Pool using C#?

 

SOLUTION:

using(ServerManager serverManager = new ServerManager())
{
   ApplicationPool pool = serverManager.ApplicationPools["AppPoolName"];

   pool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
   pool.ProcessModel.UserName = @"username";
   pool.ProcessModel.Password = @"password";

   serverManager.CommitChanges();
}

 

NOTES:

You need to add a reference to Microsoft.Web.Administration dll, located in Windows\System32\inetsrv directory

How To Disable Edit Of A Particular RadGrid Cell And Hide The Edit Control



TODO:

Have you ever wanted to remove a TextBox or other Control from a particular cell in a RadGrid?  This is particularly useful when you want to conditionally allow edits based on certain data in the record.

 

SOLUTION:

protected void rgMyGrid_ItemDataBound(object sender, GridItemEventArgs e)
{
        //do it when in edit mode
     if (e.Item.IsInEditMode && e.Item is GridEditableItem)
     {
          GridEditableItem dataItem = e.Item as GridEditableItem;

          //if we have a particular type, do not allow the cell to be edited.  if it is not this type, we can allow the cell to be edited
          if (((Employee)dataItem.DataItem).SSN == Ssn1 ||
                ((Employee)dataItem.DataItem).SSN == Ssn2)
          {
                //we have one that needs to have name edit disabled and hidden
                dataItem["Name"].Enabled = false;
                dataItem["Name"].Controls[0].Visible = false;

                //now create a label and add it to the controls of the "Name" cell.  Set the text of the label to the text that is in the edit TextBox that we hid.
                Label descLabel = new Label();
                descLabel.Text = (dataItem["Name"].Controls[0] as TextBox).Text;
                dataItem["Name"].Controls.Add(descLabel);
          }
     }
}

 

NOTES:

There are no notes on this topic

How To Read The Base64 Encoded Xml Of A WCF Message



TODO:

Have you ever wanted to get the Base64 encoded Xml of your WCF message?

 

SOLUTION:

public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
      try
      {
           //create a copy for use
           MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
           Message newMessage = buffer.CreateMessage();
          
           //assign original so it can be used again
           request = buffer.CreateMessage();
           string messageBody = string.Empty;

           //read the message
           using (XmlDictionaryReader bodyReader = newMessage.GetReaderAtBodyContents() 
           {
                bodyReader.ReadStartElement("Binary");
                byte[] bodyBytes = bodyReader.ReadContentAsBase64();
                messageBody = Encoding.UTF8.GetString(bodyBytes);
           }

           //....do your other stuff here, the messageBody will now contain your text.
      }
      catch (Exception x)
      {
            return null;
      }
}

 

NOTES:

There are no notes on this topic.

How To Display A Confirmation Dialog And Cancel The Postback When Using A Telerik RadButton



TODO:

You are using a Telerik RadButton, and you want to display a Confirm Dialog, and capture the user pressing cancel, thus canceling the Postback.

 

SOLUTION:

    <!-- Define button, and put method to call in the OnClientClicking event -->

    <telerik:RadButtonID="btnDelete"runat="server"Text="Delete Customer"OnClick="btnDelete_Click"

        OnClientClicking="ConfirmDelete">

    </telerik:RadButton>

   

    <!-- Confirm action here.  Cancel press in this dialog will return FALSE, which in turn we will catch and set cancel = true in the args -->

    <telerik:RadCodeBlockID="RadCodeBlock1"runat="server">

        <scripttype="text/javascript">

            function ConfirmDelete(sender, args) {

                if (!confirm('Delete Customer, do you wish to proceed?')) {

                    args.set_cancel(true);

                }

            }

        </script>

 

    </telerik:RadCodeBlock>

 

NOTES:

You may not need the RadCodeBlock, I did in this case due to Application

How To Force WCF Service To Use XmlSerializer Instead Of The DataContractSerializer



TODO:

Have you ever wanted to return Attributes, or have further control over serialization when using WCF?  By default, it uses the DataContractSerializer, but you can tell it to use the XmlSerializer.  

 

SOLUTION:

1.  Ensure you have your interface marked with [ServiceContract]

2.  Add XmlSerializerFormat to your method

 [ServiceContract]

 publicinterfaceIMyService


 [WebGet(UriTemplate = "employee")]

 [OperationContract]

 [XmlSerializerFormat]

 Response GetEmployees();

 

Now your WCF call will use the XmlSerializer rather than the DataContractSerializer.


NOTES:

There are no notes on this topic.

WebInvoke Verbs To Use With Restful WCF Service



TODO:

Have you ever wanted to know which verbs to use when defining your OperationContract in a WCF service?

 

SOLUTION:

// Get an employee by ID - GET - employee/id (  [WebGet(UriTemplate = "/employee/{id}")] )

// Create a new employee - POST - employee  [WebInvoke(Method = "POST", UriTemplate = "/employee/{xml}")] )

// Update an employee - PUT - employee/id  [WebInvoke(Method = "PUT", UriTemplate = "/employee/{xml}")]

// Delete an employee - DELETE - employee/id  [WebInvoke(Method = "DELETE", UriTemplate = "/employee/{id}")]

 

NOTES:

There are no notes on this topic

How To Fix "Endpoint not found" Error When Browsing Restful WCF Service In Visual Studio



TODO:

You try to view your Restful WCF service in a browser from Visual Studio and get the "Endpoint not found" error.

 

SOLUTION:

Right click on your .svc file.  Look for "Factory="= "System.ServiceModel.Activation.WebServiceHostFactory" and delete it.  You can now Right click your .svc file and choose "View in browser"

 

NOTES:

There are no notes on this topic

How To Fix The Error 'The relationship 'x' was not loaded because the type 'x' is not available' In Entity Framework



TODO:

You are attempting to query a table, and you receive the message:  The relationship 'x' was not loaded because the type 'x' is not available.

 

SOLUTION:

Ensure your connection string is exists and is valid.  If you renamed your model be sure to change the .csdl and .ssdl entry in the connection string.  Once you correct the connection string, the error will go away.

 

NOTES:

There are no notes on this topic

How To Call Stored Procedure In C# That Has Output Parameters



TODO:

Have you ever wanted to call a stored procedure in C# that has output parameters?

 

SOLUTIONS:

System.Data.Objects.ObjectParameter param1 = new ObjectParameter("paraminsp1", typeof(bool));
System.Data.Objects.ObjectParameter param2 = new ObjectParameter("paraminsp2", 0.000);           //default so EF works

using (MyEntities MyDatabase = new MyEntities())
{
     MyDatabase.sp_name(x, 2, param1, param2);
}

 

NOTES:

There are no notes on this topic