Home Account Search
tsql substring and charindex example. first initial and last name

The sql code below will take the first character and then the rest of the character s from the space index.

john doe will be returned as jdoe.  can use any delimiter in charindex.  Add one to the int that charindex returns and the len(column) function to get the rest of the values.

substring([full name],1,1) + substring([full name],CHARINDEX (' ' ,[full name]) +1,len([full name])) [UserName]

C# magento enterprise API stock update procedure
Need to use product_id and not sku!  use sku to get item and then set product_id
one example of one item.
public string UpdateInventory(string sku, int inStock, string stkQty)
        {
            if (string.IsNullOrEmpty(this.SessionId))
                this.Login();
            try
            {
                string prodID = string.Empty ;
                catalogInventoryStockItemEntity ie = new catalogInventoryStockItemEntity();
               
                MagentoPushPullService.MagentoWebService.catalogInventoryStockItemUpdateEntity cisi = new catalogInventoryStockItemUpdateEntity();
                cisi.is_in_stock = inStock;
                cisi.qty = stkQty;
                cisi.is_in_stockSpecified = true;
               
// you can pass in more than one product at a time by setting/passing in an array of strings
                string[] item = new string[1] ;
                item[0] = sku;
               
                foreach (catalogInventoryStockItemEntity  sie in   magentoService.catalogInventoryStockItemList(this.SessionId,item))
                {
                    prodID = sie.product_id ;
                }
  // Update product by product id from StockItemList call
                int i;
                i = magentoService.catalogInventoryStockItemUpdate(this.SessionId, prodID, cisi);
                foreach (catalogInventoryStockItemEntity sie in magentoService.catalogInventoryStockItemList(this.SessionId, item))
                {
                    string tmp = sie.is_in_stock;
                }
              
                return "Success";
            }
            catch (Exception ex)
            {
                //TODO: Log the error               
                return "Error updating inventory";
            }
          
        }
 
tsql send email

using existing sql mail profile.

EXEC msdb.dbo.sp_send_dbmail

@profile_name = 'ReportsMail',

@recipients = @emailto,

@body = @body,

@blind_copy_recipients = 'add addresses here',

@subject = @subject;

TSQL calcualte number of business days between 2 dates
CREATE FUNCTION dbo.GetWorkingDays  
(  
    @startDate SMALLDATETIME,  
    @endDate SMALLDATETIME  

RETURNS INT  
AS  
BEGIN 
    DECLARE @range INT; 
 
    SET @range = DATEDIFF(DAY, @startDate, @endDate)+1; 
 
    RETURN  
    ( 
        SELECT  
            @range / 7 * 5 + @range % 7 -  
            ( 
                SELECT COUNT(*)  
            FROM 
                ( 
                    SELECT 1 AS d 
                    UNION ALL SELECT 2  
                    UNION ALL SELECT 3  
                    UNION ALL SELECT 4  
                    UNION ALL SELECT 5  
                    UNION ALL SELECT 6  
                    UNION ALL SELECT 7 
                ) weekdays 
                WHERE d <= @range % 7  
                AND DATENAME(WEEKDAY, @endDate - d + 1)  
                IN 
                ( 
                    'Saturday', 
                    'Sunday' 
                ) 
            ) 
    ); 
END  
GO 
 
c# send mail function

quick and easy way to send email to many to addresses.

public static void SendMessageEmail(string eTO, string From, string Subject, string message, bool isHtml)

{

MailMessage msg = new MailMessage();

char split = Convert.ToChar(";");

string[] emTo = eTO.Split(split);

foreach (string toAdd in emTo)

{

msg.To.Add(toAdd);

}

msg.From = new MailAddress(From);

msg.Subject = Subject;

msg.Body = message;

msg.IsBodyHtml = isHtml;

SmtpClient client = new SmtpClient("mail.yourserver.com");

try

{client.Send(msg);}

catch (Exception exc) {//do something to handle error here }}

Max HTTP request size setting

put this in web config file.

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="4096" />
    </system.web>
</configuration>

length =  4,096 kilobytes (KB) (or 4MB)

Magento Enterprise API row total issue

When pulling records from sales_order, I discovered that the row_total field has values > 0 for lines with 100% discount! You must subtract discount_amount to get extended price.

this.ExtendedPrice = Convert.ToDecimal(item.row_total )-Convert.ToDecimal(item.discount_amount );

Crystal Reports keep together setting for groups
To keep all of the detail records for a group together on a page by checking the "Keep Group Together" box in the change group options window. This will force the group to start on the next page if all of the records can not be shown on the same page.
Keep appSettings or connectionStrings values in file other than web.config
add values below to web.config file appSettings configSource = "App_Data\appSettings.config" connectionStrings configSource ="App_Data\connectionStrings.config" example ?xml version="1.0" encoding="utf-8" ? connectionStrings add name="conn" connectionString="Server=localhost; Initial Catalog=sql_db;Intergrated Security=True" connectionStrings
asp.net MaskedEditValidator with validation summary
If you are using a mask on a text box for a phone number and you want to keep the format after lost focus you will need to set the initial value to the mask to get the validation to work.
modification of asp.net/ajax sample
asp:TextBox ID="TextBox2" runat="server" Width="130px" Height="16px" ValidationGroup="MKE" /> ajaxToolkit:MaskedEditExtender ID="MaskedEditExtender2" runat="server" TargetControlID="TextBox2" Mask="999-999-9999" MessageValidatorTip="true" OnFocusCssClass="MaskedEditFocus" OnInvalidCssClass="MaskedEditError" MaskType="None" InputDirection="RightToLeft" AcceptNegative="Left" DisplayMoney="Left" ErrorTooltipEnabled="True" /> ajaxToolkit:MaskedEditValidator ID="MaskedEditValidator2" runat="server" ControlExtender="MaskedEditExtender2" ControlToValidate="TextBox2" IsValidEmpty="False" InitialValue="___-___-____" MaximumValue="12000" EmptyValueMessage="Number is required" InvalidValueMessage="Number is invalid" MaximumValueMessage="Number > 12000" MinimumValueMessage="Number < -100" MinimumValue="-100" Display="Dynamic" TooltipMessage="Input a number from -100 to 12000" EmptyValueBlurredText="*" InvalidValueBlurredMessage="*" MaximumValueBlurredMessage="*" MinimumValueBlurredText="*" ValidationGroup="MKE" />
TSQL mm/yyyy date format
select right('00' + convert(varchar(2),month(getdate())),2) + '/' + cast(datepart(yyyy,getdate()) as varchar(4)) result 12/2009 will sort correctly
vb.net create class of classes with IList
'create class
Public Class PayrollRecord Public Sub New() End Sub Private _inactiveFL As Boolean Private _amount As String Private _userID As String Private _empID As String Private _total As String Public Property InactiveFl() As Boolean Get Return _inactiveFL End Get Set(ByVal value As Boolean) _inactiveFL = value End Set End Property Public Property Amount() As String Get Return _amount End Get Set(ByVal value As String) _amount = value End Set End Property Public Property UserId() As String Get Return _userID End Get Set(ByVal value As String) _userID = value End Set End Property Public Property EmpId() As String Get Return _empID End Get Set(ByVal value As String) _empID = value End Set End Property Public Property Total() As String Get Return _total End Get Set(ByVal value As String) _total = value End Set End Property End Class
Imports System.Collections.Generic
'create generic collection Dim payroll As IList(Of PayrollRecord) = New List(Of PayrollRecord)
'Add records to payroll object. Dim pRoll As New PayrollRecord() pRoll.Amount = Amount pRoll.EmpId = EmpId pRoll.InactiveFl = InactiveFl pRoll.UserId = UserId pRoll.Total = Total payroll.Add(pRoll)
'loop thru each item in the payroll object For Each drow As PayrollRecord In payroll Write(CompId & "," & OrgId & "," & drow.EmpId.Trim & "," & drow.Amount & "," & drow.Total & "," & drow.UserId) Next
Retrieving the COM class factory for component with CLSID {…} failed due to the following error: 80040154

I have found this error is probably due to a dll not being registered on the target machine.

reg file below will add right click menu item to register or unregister files

create .reg file with the contents below and merge into the registry.

REGEDIT4

[HKEY_CLASSES_ROOT\.dll]
@="dllfile"

[HKEY_CLASSES_ROOT\.ocx]
@="ocxfile"

[HKEY_CLASSES_ROOT\.olb]
@="olbfile"

[HKEY_CLASSES_ROOT\.exe]
@="exefile"


[HKEY_CLASSES_ROOT\dllfile\shell\Register\command]
@="regsvr32.exe \"%1\""

[HKEY_CLASSES_ROOT\ocxfile\shell\Register\command]
@="regsvr32.exe \"%1\""

[HKEY_CLASSES_ROOT\olbfile\shell\Register\command]
@="regsvr32.exe \"%1\""

[HKEY_CLASSES_ROOT\exefile\shell\Register\command]
@="\"%1\" /register"

[HKEY_CLASSES_ROOT\dllfile\shell\Register (Silent)\command]
@="regsvr32.exe /s \"%1\""

[HKEY_CLASSES_ROOT\ocxfile\shell\Register (Silent)\command]
@="regsvr32.exe /s \"%1\""

[HKEY_CLASSES_ROOT\olbfile\shell\Register (Silent)\command]
@="regsvr32.exe /s \"%1\""

 

[HKEY_CLASSES_ROOT\dllfile\shell\UnRegister\command]
@="regsvr32.exe /u \"%1\""

[HKEY_CLASSES_ROOT\ocxfile\shell\UnRegister\command]
@="regsvr32.exe /u \"%1\""

[HKEY_CLASSES_ROOT\olbfile\shell\UnRegister\command]
@="regsvr32.exe /u \"%1\""

[HKEY_CLASSES_ROOT\exefile\shell\UnRegister\command]
@="\"%1\" /unregister"

[HKEY_CLASSES_ROOT\dllfile\shell\UnRegister (Silent)\command]
@="regsvr32.exe /u /s \"%1\""

[HKEY_CLASSES_ROOT\ocxfile\shell\UnRegister (Silent)\command]
@="regsvr32.exe /u /s \"%1\""

[HKEY_CLASSES_ROOT\olbfile\shell\UnRegister (Silent)\command]
@="regsvr32.exe /u /s \"%1\""

Obout Grid v6.0.4 Programmatic only filter
add java script function filterGrid(ddl) { if (ddl.value == '*') { Grid1.removeFilter(); } else { Grid1.addFilterCriteria('AccountRep', OboutGridFilterCriteria.EqualTo, ddl.value); Grid1.executeFilter(); } } set grid to AllowFiltering="True" and FilterType="ProgrammaticOnly" if (!Page.IsPostBack) { ddlReps.Attributes["onchange"] = "filterGrid(this)"; }
Magento Enterprise get sales order list
create web reference to wsdl AIP Reference here
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MagentoPushPull.com.renewlife.staging; using System.Security.Cryptography.X509Certificates; using System.Configuration; using System.Net; using System.Net.Security; private void button1_Click(object sender, EventArgs e) { TypeClient ws = new Mage_Api_Model_Server_V2_HandlerPortTypeClient(); MagentoService ws = new MagentoService(); string wsSessionID = string.Empty; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(myCertificateValidation); //X509Certificate clientCert = X509Certificate.CreateFromCertFile(ConfigurationSettings.AppSettings["ClientCertDir"]); //ws.ClientCertificates.Add(clientCert); textBox1.Text = "login" + "\r\n"; wsSessionID = ws.login("user", "api_key"); ws.salesOrderListCompleted += new salesOrderListCompletedEventHandler(ws_salesOrderListCompleted); textBox1.Text = textBox1.Text + "call sales order async " + "\r\n"; ws.salesOrderListAsync(wsSessionID, null, ws); } void ws_salesOrderListCompleted(object sender, salesOrderListCompletedEventArgs e) { salesOrderEntity[] soe = e.Result ; if (soe.Length > 0) { foreach (salesOrderEntity msoe in soe) { try { textBox1.Text = textBox1.Text + "" + msoe.order_id + " " + msoe.grand_total + "\r\n"; MagentoService ws = new MagentoService(); string wsSessionID = string.Empty; textBox1.Text = "get order detail" + "\r\n"; wsSessionID = ws.login("user", "api_key"); ws.salesOrderInfoCompleted += new salesOrderInfoCompletedEventHandler(ws_salesOrderInfoCompleted); //salesOrderEntity soInfo = ws.salesOrderInfo(wsSessionID, msoe.increment_id); // foreach (salesOrderItemEntity soie in soInfo.items) // { // textBox1.Text = soie.sku + "\r\n"; // } ws.salesOrderInfoAsync(wsSessionID, msoe.increment_id,ws); } catch (Exception merror) { MessageBox.Show("" + msoe.order_id + "" + merror.ToString()); } } } else { textBox1.Text = textBox1.Text + "No orders" + "\r\n"; } } void ws_salesOrderInfoCompleted(object sender, salesOrderInfoCompletedEventArgs e) { salesOrderEntity soe = e.Result; if (soe.items.Length > 0) { foreach (salesOrderItemEntity soie in soe.items) { textBox1.Text = "order detail - " + soie.sku + " " + soie.name + "\r\n"; } } }
Building Web Service Clients using the .NET Framework
Good article on consuming web services and creating classes and dll's Here
tsql search for text in all stored procedures
select * from sysobjects where id in ( select ID from syscomments where ltrim(Rtrim([text])) like '%ProductInfo%') returns the names of procedures that contain the text string
C# Sql Transaction Example
Create Transaction object and use test to check sql result. If result is bad then use rollback method uses System.Data.Common Create connection object DbConnection myConn = myDB.CreateConnection(); Using (myConn){ myConn.Open(); DbTransaction myTran = myConn.BeginTransaction(); cmdInsert.Connection = myConn; cmdInsertt.Transaction = myTran; cmdInsert.ExecuteNonQuery(); mastID = Convert.ToInt32(cmdInsert.Parameters["@RecordID"].Value); if (mastID > 0 ) { myTran.Commit(); } else { myTran.Rollback(); } }
C# Create DataSet Relations and bind to TreeView.

Used to create 3 level TreeView.

protected void PopNav() {

tvNav.Nodes.Clear();

DAL dLayer = new DAL();

DataSet ds = dLayer.GetNavCategory();

ds.Relations.Add("CatToProd", ds.Tables["Cat"].Columns["Category"], ds.Tables["Prod"].Columns["Category"]);

ds.Relations.Add("ProdToFile", ds.Tables["Prod"].Columns["productid"], ds.Tables["FileTypes"].Columns["productid"]);

TreeNode nodeCat;

TreeNode nodeProd;

TreeNode nodeFile;

foreach (DataRow rowCat in ds.Tables["Cat"].Rows)

{

nodeCat = new TreeNode();

nodeCat.Expanded = false;

nodeCat.SelectAction = TreeNodeSelectAction.Expand;

nodeCat.Text = rowCat["Category"].ToString();

tvNav.Nodes.Add(nodeCat);

foreach (DataRow rowProd in rowCat.GetChildRows("CatToProd"))

{

nodeProd = new TreeNode();

nodeProd.Expanded = false;

nodeProd.Text = rowProd["ShortDescription"].ToString();

nodeProd.Value = rowProd["productid"].ToString();

nodeCat.ChildNodes.Add(nodeProd);

foreach (DataRow rowFileType in rowProd.GetChildRows("ProdToFile"))

{

nodeFile = new TreeNode();

nodeFile.Text = rowFileType["FileType"].ToString();

nodeFile.Value = rowFileType["productid"].ToString();

nodeProd.ChildNodes.Add(nodeFile);

}

}

}

}

///////////////DAL method

public DataSet GetNavCategory()

{

DataSet ds = new DataSet();

SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["RenewLifeConnStr"].ConnectionString);

string sql = @"dbo.GetAllCategories";

string sqlProd = @"dbo.GetAllCategoryDescriptions";

string sqlFileType = @"dbo.GetAllFileTypesByProduct";

SqlDataAdapter daCat = new SqlDataAdapter(sql, cn);

SqlDataAdapter daProd = new SqlDataAdapter(sqlProd, cn);

SqlDataAdapter daFileType = new SqlDataAdapter(sqlFileType, cn);

daCat.SelectCommand.CommandType = CommandType.StoredProcedure;

daCat.SelectCommand.CommandTimeout = 20000;

daProd.SelectCommand.CommandType = CommandType.StoredProcedure;

daProd.SelectCommand.CommandTimeout = 20000;

daFileType.SelectCommand.CommandType = CommandType.StoredProcedure;

daFileType.SelectCommand.CommandTimeout = 20000;

using (cn)

{

cn.Open();

daCat.Fill(ds, "Cat");

daProd.Fill(ds, "Prod");

daFileType.Fill(ds, "FileTypes");

}

return ds;

}

tsql divide by zero fix
good example below on how to use the NULLIF() function
here

select sum((xtndprce-extcost)/NULLIF(xtndprce,0)) as ActualMargin

I used in a group by select